Preliminary study on Golang and Beego

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Http://beego.me/docs/mvc/model/object.md


Entry file Main.go

Package Main


Import (
"Github.com/astaxie/beego"
"Github.com/astaxie/beego/orm"
_ "Github.com/go-sql-driver/mysql"
"Testslim/models"
_ "Testslim/routers"
)


Func init () {
Orm. Registerdriver ("MySQL", Orm.) Dr_mysql)
Orm. RegisterDatabase ("Default", "MySQL", "test:pwd@tcp (ip:3306)/tablename?charset=utf8")
Orm. Registermodelwithprefix ("He_", New (models). Students))
}


Func Main () {
Beego. Run ()
}

The model file is stored in the models directory

Models.go:

Package Models


Type Students struct {
Id int
Nickname string
Createtime int
}


Storage controller in the Controllers directory

Package controllers


Import (
"FMT"
"Github.com/astaxie/beego"
"Github.com/astaxie/beego/orm"
_ "Github.com/go-sql-driver/mysql"
"Testslim/models"
"Time"
)

Func (t *testcontroller) Testmodel () {
o: = orm. Neworm ()
O.using ("Default")


Ins
Student: = new (models. Students)
Student. Nickname = "Test from Go"
Student. createtime = Int (time. Now (). Unix ())
Fmt. Println (O.insert (student))


Read
Student: = models. STUDENTS{ID:10001}
ERR: = O.read (&student)
If Err = = orm. errnorows {
//t.data["json"] = "No rows"
} else If Err = = orm. ERRMISSPK {
//t.data["json"] = "No PK"
} else {
//t.data["JSON"] = Student
// }


var STDs []*models. Students
O.querytable ("He_students"). Limit (10). All (&stds)
t.data["json"] = map[string][]*models. students{"STDs": STDs}
T.servejson ()
}


Finally, configure router.go in the routing routers

Package routers


Import (
"Github.com/astaxie/beego"
"Testslim/controllers"
)


Func init () {
Beego. Router ("/", &controllers. maincontroller{})
Beego. Router ("/test", &controllers. testcontroller{})
Beego. Autorouter (&controllers. testcontroller{})
}


Use the above operation to complete a simple set of interfaces

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.