Golang's Gin framework introductory teaching

Source: Internet
Author: User
学习Golang差不多有一个星期时间,开始自己做点小功能,练练手。

Gin Introduction

Gin 是一个 Golang 写的 web 框架,具有高性能的优点,,基于 httprouter,它提供了类似martini但更好性能(路由性能约快40倍)的API服务。官方地址:https://github.com/gin-gonic/gin

Installation Framework

Configure Gopath, recommend yourself to build a project in Gopath, here I use aze.org as a project directory.

$ go Get github.com/gin-gonic/gin

Install MySQL Driver

$ go Get github.com/go-sql-driver/mysql

Organizing projects

With the separation of the model and handler above, the code structure becomes clearer, but we are still a single file. The next step is to encapsulate the different packages.

Database processing

Create the following three folders in the project root directory, apis,databases and models, and create files within the folder. At this point our catalog results are as follows

apis文件夹存放我们的handler函数,models文件夹用来存放我们的数据模型。

mysql.go

package databaseimport ( "database/sql" _ "github.com/go-sql-driver/mysql" "log")var SqlDB *sql.DBfunc init() { var err error SqlDB, err = sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/test?parseTime=true") if err != nil {  log.Fatal(err.Error()) } err = SqlDB.Ping() if err != nil {  log.Fatal(err.Error()) }}

Because we need to use the SQLDB variable in other places, the variable name must be capitalized, according to Golang's custom.

Data Model Package

Modify the Person.go in the Models folder to move the corresponding person structure and its methods here:

package modelsimport ( "log" db "newland/database")type Person struct { Id        int    `json:"id" form:"id"` FirstName string `json:"first_name" form:"first_name"` LastName  string `json:"last_name" form:"last_name"`}func (p *Person) AddPerson() (id int64, err error) { rs, err := db.SqlDB.Exec("INSERT INTO person(first_name, last_name) VALUES (?, ?)", p.FirstName, p.LastName) if err != nil {  return } id, err = rs.LastInsertId() return}func (p *Person) GetPersons() (persons []Person, err error) { persons = make([]Person, 0) rows, err := db.SqlDB.Query("SELECT id, first_name, last_name FROM person") defer rows.Close() if err != nil {  return } for rows.Next() {  var person Person  rows.Scan(&person.Id, &person.FirstName, &person.LastName)  persons = append(persons, person) } if err = rows.Err(); err != nil {  return } return}..............

Handler

The specific handler function is then encapsulated in the API package because the handler function operates the database, so it references the model package

package apisimport ( "net/http" "log" "fmt" "github.com/gin-gonic/gin" . "aze.org/models")func IndexApi(c *gin.Context) { c.String(http.StatusOK, "It works")}func AddPersonApi(c *gin.Context) { firstName := c.Request.FormValue("first_name") lastName := c.Request.FormValue("last_name") p := Person{FirstName: firstName, LastName: lastName} ra, err := p.AddPerson() if err != nil {  log.Fatalln(err) } msg := fmt.Sprintf("insert successful %d", ra) c.JSON(http.StatusOK, gin.H{  "msg": msg, })}......

Routing

Finally, we pull out the route, modify the Router.go, we encapsulate the routing function in the routing file.

package mainimport ( "github.com/gin-gonic/gin" . "aze.orgd/apis")func initRouter() *gin.Engine { router := gin.Default() router.GET("/", IndexApi) router.POST("/person", AddPersonApi) router.GET("/persons", GetPersonsApi) router.GET("/person/:id", GetPersonApi) router.PUT("/person/:id", ModPersonApi) router.DELETE("/person/:id", DelPersonApi) return router}

App Portal

Finally, the main function of the app portal, the route is imported, and we want to close the main function at the end of the global database connection pool:

Main.go

package mainimport ( db "aze.org/database")func main() { defer db.SqlDB.Close() router := initRouter() router.Run(":8000")}

Run the project at this point, not as simple as before to use go run main.go, because the package main contains Main.go and router.go files, so need to run the Go Run *.go command compile run. If it is the final compiled binary project, run the Go Build-o app and generate the app file directly./app can run the project.

Summarize

1. Through the above practice, we understand the gin framework to create basic restful services.
2.golang keyword is not many, but the syntax is quite a lot of, need to study hard, lay a good foundation.
3. Look at the good frame, and then think about whether there is a better wording.

Reference Tutorial:

Gin Framework Detail document address: Https://godoc.org/github.com/gin-gonic/gin

Project Address:

Https://github.com/onebig32/gin-learn.git

Related Article

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.