This is a creation in Article, where the information may have evolved or changed.
Win10+go+beego Building User Management System
After two days of study from scratch, go program user CRUD System finally build success, very good yo.
Go Environment Building
Download Go1.9rc2.windows-amd64.msi, as Golang is wall, can only be downloaded from other websites.
With the default installation to C:\Go, open the command line and enter Go version
C:\users\steve>go version
Go version go1.9rc2 windows/amd64
Create C:\GOPATH folder, add environment variable
Go development Tool installation configuration
Download Eclipse-inst-win64.exe (4.6.3) and install
Installing the Goclipse Plugin
Because GFC is closed, we need to https://github.com/GoClipse/goclipse.github.io/archive/master.zip download the Goclipse installation package and unzip it first. Then open eclipse (make sure that you already have the CDT), Help, install New software ..., then choose the Add button, enter the unpacked release directory, select Goclipse, and then continue with next to install successfully. You will need to restart eclipse after the installation is complete.
Tick Goclipse, next to complete
Open: Window>preferences
Download Gocode.exe,guru.exe,godef.exe can also not be configured
Beego Installation
Download and install the GIT bash tool.
Open Gitbash, enter go get github.com/astaxie/beego. Wait a moment to see the \github.com\astaxie\beego directory in the SRC directory of the Gopath.
Enter go get Github.com/beego/bee in Gitbash. Wait a moment to see the \github.com\beego\bee directory in the SRC directory of Gopath and a lot of dependent packages are downloaded to the \github.com directory.
New Project
CD%GOPATH%/SRC
Bee New Hello
CD Hello
Bee Run Hello
You can see the results of the operation in the browser input 127.0.0.1:8080 (Welcome to Beego's Welcome page)
Goeclipse Development
Open Eclipse, import Hello Project
Create a new file with the following structure
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, "delete succeeded")
}
}
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, "added success")
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, "modified successfully")
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 to 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). ("-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.Birthuser.Remark = u.Remarkuser.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["Ema Il "] = u.email
}
If Len (U.birth) > 0 {
//TM, _: = time. Parse ("2006-02-02", U.birth)//date string to timestamp
//user["Birth"] = StrConv. Formatint (TM. Unix (), ten)
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 "}}
Command line Start Bee
(You can start hello.exe directly later)
Browser opens http://localhost:8080/