win10+go+beego搭建用户管理系统
经过两天的从零开始研究学习,go程序的用户crud系统终于搭建成功,很不错吆。
go环境搭建
下载go1.9rc2.windows-amd64.msi,由于golang被墙,只能从其他网上下载。
采用默认安装到C:\Go,打开命令行,输入go version
C:\Users\steve>go version
go version go1.9rc2 windows/amd64创建C:\GOPATH文件夹,添加环境变量
go开发工具安装配置
下载eclipse-inst-win64.exe(4.6.3)并安装
安装goclipse插件
因为GFC的封闭,我们需要先到https://github.com/GoClipse/goclipse.github.io/archive/master.zip下载GoClipse的安装包,并解压。然后打开Eclipse(确保已经包含CDT),Help -> Install New Software…,然后选择Add按钮,输入解压后的Release目录,选择GoClipse,然后一直next就安装成功了。安装完成后需要重启Eclipse。
![]()
勾选goclipse,下一步直至完成
打开:Window>Preferences
![]()
下载gocode.exe,guru.exe,godef.exe也可以不配置
Beego安装
下载并安装好Git bash工具
打开gitbash,输入 go get github.com/astaxie/beego 。稍等片刻即可在GOPATH的src目录下看到有\github.com\astaxie\beego目录。
在gitbash中输入 go get github.com/beego/bee 。稍等片刻即可在GOPATH的src目录下看到有\github.com\beego\bee目录,同时有很多依赖包被下载添加到\github.com目录下。
新建项目
cd %GOPATH%/src
bee new hello
cd hello
bee run hello
在浏览器输入127.0.0.1:8080就看到了运行结果(welcome to beego的欢迎页)
goeclipse开发
打开eclipse,导入hello项目
新建文件,结构如下
app.conf
appname = hello
httpport = 8080
runmode = dev
db.host = localhost
db.port = 3306
db.user = root
db.pass = 123456
db.name = test
db.timezone = Asia/Shanghai
default.go
package controllers
import (
“github.com/astaxie/beego”
)
type MainController struct {
beego.Controller
}
func (c *MainController) Get() {
// c.Data[“Website”] = “beego.me”
// c.Data[“Email”] = “astaxie@gmail.com”
c.TplName = “user/usermanage.html”
}
func (c *MainController) Rsp(status bool, str string) {
c.Data[“json”] = &map[string]interface{}{“succ”: status, “msg”: str}
c.ServeJSON()
}
user.go
package controllers
import (
“fmt”
m “hello/models”
)
type UserController struct {
MainController
}
func (this *UserController) Index() {
user := this.GetSession(“userinfo”)
if user != nil {
this.Data[“userinfo”] = user
this.TplName = “main.html”
return
}
this.Redirect(“/”, 302)
}
func (this *UserController) UserIndex() {
this.TplName = “user/usermanage.html”
}
func (this *UserController) UserList() {
page, _ := this.GetInt64(“page”)
pageSize, _ := this.GetInt64(“rows”)
u := m.User{}
if this.GetString(“id”) != “” {
u.Id, _ = this.GetInt(“id”)
}
if this.GetString(“name”) != “” {
u.Name = this.GetString(“name”)
}
if this.GetString(“phone”) != “” {
u.Phone = this.GetString(“phone”)
}
nodes, cnt := m.GetUserList(page, pageSize, &u)
fmt.Println(cnt)
this.Data[“json”] = &map[string]interface{}{“total”: cnt, “rows”: &nodes}
this.ServeJSON()
}
func (this *UserController) UserDel() {
idstr := this.GetString(“ids”)
err := m.DelUser(idstr)
if err != nil {
this.Rsp(false, err.Error())
} else {
this.Rsp(true, “删除成功”)
}
}
func (this *UserController) UserAdd() {
u := m.User{}
u.Id, _ = this.GetInt(“Id”)
if err := this.ParseForm(&u); err != nil {
this.Rsp(false, err.Error())
return
}
id, err := m.AddUser(&u)
if err == nil && id > 0 {
this.Rsp(true, “新增成功”)
return
} else {
this.Rsp(false, err.Error())
return
}
}
func (this *UserController) UserUpdate() {
u := m.User{}
if err := this.ParseForm(&u); err != nil {
this.Rsp(false, err.Error())
return
}
id, err := m.UpdateUser(&u)
if err == nil && id > 0 {
this.Rsp(true, “修改成功”)
return
} else {
this.Rsp(false, err.Error())
return
}
}
func (this *UserController) UserUpload() {
f, fh, err := this.GetFile("uploadFile")
defer f.Close()
if err != nil {
fmt.Println("get file error ", err)
this.Data["json"] = &map[string]interface{}{"path": "", "succ": false}
this.ServeJSON()
} else {
fmt.Println(fh.Filename)
this.SaveToFile("uploadFile", "static/upload/"+fh.Filename)
this.Data["json"] = &map[string]interface{}{"path": "/static/upload/" + fh.Filename, "succ": true}
this.ServeJSON()
}
}
init.go
package models
import (
“fmt”
“github.com/astaxie/beego”
“github.com/astaxie/beego/orm”
_ “github.com/go-sql-driver/mysql”
“net/url”
)
func init() {
dbhost := beego.AppConfig.String(“db.host”)
dbport := beego.AppConfig.String(“db.port”)
dbname := beego.AppConfig.String(“db.name”)
dbuser := beego.AppConfig.String(“db.user”)
dbpass := beego.AppConfig.String(“db.pass”)
timezone := beego.AppConfig.String(“db.timezone”)
if dbport == “” {
dbport = “3306”
}
dsn := dbuser + “:” + dbpass + “@tcp(” + dbhost + “:” + dbport + “)/” + dbname + “?charset=utf8”
// dsn := “root:123456@/test?charset=utf8”
if timezone != “” {
dsn = dsn + “&loc=” + url.QueryEscape(timezone)
}
fmt.Println(dsn)
orm.RegisterDataBase(“default”, “mysql”, dsn, 5, 30)
if beego.AppConfig.String(“runmode”) == “dev” {
orm.Debug = true
}
}
user.go
package models
import (
“errors”
“fmt”
“log”
“strconv”
“strings”
“time”
"github.com/astaxie/beego/orm"
"github.com/astaxie/beego/validation"
)
type User struct {
Id int
Name string form:"name" valid:"Required;MaxSize(20);MinSize(6)"
Pass string form:"pass" valid:"Required;MaxSize(20);MinSize(6)"
Email string form:"email" valid:"Required;Email"
Phone string form:"phone" valid:"Required;Mobile"
Image string form:"image" valid:"MaxSize(50);MinSize(6)"
Addr string form:"addr" valid:"MaxSize(30)" form:"name"
Regtime string
Birth string form:"birth"
Remark string valid:"MaxSize(200)" form:"remark"
}
func init() {
orm.RegisterModel(new(User))
}
func (u *User) TableName() string {
return “t_user”
}
func (this *User) ToString() string {
return fmt.Sprintf(“Id:%d\tName:%s”, this.Id, this.Name)
}
func checkUser(u *User) (err error) {
valid := validation.Validation{}
b, _ := valid.Valid(&u)
if !b {
for _, err := range valid.Errors {
log.Println(err.Key, err.Message)
return errors.New(err.Message)
}
}
return nil
}
func GetUserList(page int64, pageSize int64, user *User) (userlist []*User, count int64) {
o := orm.NewOrm()
qs := o.QueryTable(“t_user”)
var offset int64
if page > 1 {
offset = (page - 1) * pageSize
}
if user.Id != 0 {
qs = qs.Filter(“id__exact”, user.Id)
}
if user.Phone != “” {
qs = qs.Filter(“phone__contains”, user.Phone)
}
if user.Name != “” {
qs = qs.Filter(“name__contains”, user.Name)
}
qs.Limit(pageSize, offset).OrderBy(“-Id”).All(&userlist)
count, _ = qs.Count()
return userlist, count
}
func DelUser(idstr string) error {
ids := strings.Split(idstr, “,”)
num, err := orm.NewOrm().QueryTable(“t_user”).Filter(“id__in”, ids).Delete()
if num > 0 && err == nil {
return nil
} else {
return err
}
}
func AddUser(u *User) (int64, error) {
if err := checkUser(u); err != nil {
return 0, err
}
o := orm.NewOrm()
user := new(User)
user.Name = u.Name
user.Email = u.Email
user.Phone = u.Phone
user.Image = u.Image
user.Addr = u.Addr
// tm2, _ := time.Parse("2006-02-02", u.Birth) //日期字符串转为时间戳
// user.Birth = strconv.FormatInt(tm2.Unix(), 10)
user.Birth = u.Birth
user.Remark = u.Remark
user.Regtime = strconv.FormatInt(time.Now().Unix(), 10) //获取当前时间戳
id, err := o.Insert(user)
return id, err
}
func UpdateUser(u *User) (int64, error) {
if err := checkUser(u); err != nil {
return 0, err
}
o := orm.NewOrm()
user := make(orm.Params)
if len(u.Name) > 0 {
user[“Name”] = u.Name
}
if len(u.Phone) > 0 {
user[“Phone”] = u.Phone
}
if len(u.Addr) > 0 {
user[“Addr”] = u.Addr
}
if len(u.Email) > 0 {
user[“Email”] = u.Email
}
if len(u.Birth) > 0 {
// tm, _ := time.Parse(“2006-02-02”, u.Birth) //日期字符串转为时间戳
// user[“Birth”] = strconv.FormatInt(tm.Unix(), 10)
user[“Birth”] = u.Birth
}
if len(u.Image) > 0 {
user[“Image”] = u.Image
}
if len(u.Remark) > 0 {
user[“Remark”] = u.Remark
}
if len(user) == 0 {
return 0, errors.New(“update field is empty”)
}
var table User
num, err := o.QueryTable(table).Filter(“Id”, u.Id).Update(user)
return num, err
}
func GetUserByUsername(username string) (user User) {
user = User{Name: username}
o := orm.NewOrm()
o.Read(&user, “Name”)
return user
}
router.go
package routers
import (
“github.com/astaxie/beego”
“hello/controllers”
)
func init() {
beego.Router(“/”, &controllers.MainController{})
beego.Router(“/usermanage”, &controllers.UserController{}, “*:UserIndex”)
beego.Router(“/user/list”, &controllers.UserController{}, “*:UserList”)
beego.Router(“/user/add”, &controllers.UserController{}, “*:UserAdd”)
beego.Router(“/user/del”, &controllers.UserController{}, “*:UserDel”)
beego.Router(“/user/update”, &controllers.UserController{}, “*:UserUpdate”)
beego.Router(“/user/upload”, &controllers.UserController{}, “*:UserUpload”)
}
usermanage.html
{{template “../user/header.tpl”}}
命令行启动bee
(以后可以直接启动hello.exe)