Gin 介绍
Gin 是一个 Golang 写的 web 框架,具有高性能的优点,,基于 httprouter,它提供了类似martini但更好性能(路由性能约快40倍)的API服务。官方地址:https://github.com/gin-gonic/gin
安装框架
配置好GOPATH,建议自己在GOPATH建个项目,这里我以Go_GinStart作为项目目录。
$ go get github.com/gin-gonic/gin
安装mysql驱动
$ go get github.com/go-sql-driver/mysql
项目组织结构
在项目根目录创建下面三个文件夹,apis,databases和models,并在文件夹内创建文件。
-
apis文件夹存放我们的handler函数
-
models文件夹用来存放我们的数据模型
1 package database 2 3 import ( 4 "database/sql" 5 _ "github.com/go-sql-driver/mysql" 6 "log" 7 ) 8 9 var SqlDB *sql.DB 10 11 func init() { 12 var err error 13 SqlDB, err = sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/test?parseTime=true") 14 if err != nil { 15 log.Fatal(err.Error()) 16 } 17 err = SqlDB.Ping() 18 if err != nil { 19 log.Fatal(err.Error()) 20 } 21 }
1 package models 2 3 import ( 4 "log" 5 db "newland/database" 6 ) 7 8 type Person struct { 9 Id int `json:"id" form:"id"` 10 FirstName string `json:"first_name" form:"first_name"` 11 LastName string `json:"last_name" form:"last_name"` 12 } 13 14 func (p *Person) AddPerson() (id int64, err error) { 15 rs, err := db.SqlDB.Exec("INSERT INTO person(first_name, last_name) VALUES (?, ?)", p.FirstName, p.LastName) 16 if err != nil { 17 return 18 } 19 id, err = rs.LastInsertId() 20 return 21 } 22 23 func (p *Person) GetPersons() (persons []Person, err error) { 24 persons = make([]Person, 0) 25 rows, err := db.SqlDB.Query("SELECT id, first_name, last_name FROM person") 26 defer rows.Close() 27 28 if err != nil { 29 return 30 } 31 32 for rows.Next() { 33 var person Person 34 rows.Scan(&person.Id, &person.FirstName, &person.LastName) 35 persons = append(persons, person) 36 } 37 if err = rows.Err(); err != nil { 38 return 39 } 40 return 41 }
1 package apis 2 3 import ( 4 "net/http" 5 "log" 6 "fmt" 7 "github.com/gin-gonic/gin" 8 . "aze.org/models" 9 ) 10 11 func IndexApi(c *gin.Context) { 12 c.String(http.StatusOK, "It works") 13 } 14 15 func AddPersonApi(c *gin.Context) { 16 firstName := c.Request.FormValue("first_name") 17 lastName := c.Request.FormValue("last_name") 18 19 p := Person{FirstName: firstName, LastName: lastName} 20 21 ra, err := p.AddPerson() 22 if err != nil { 23 log.Fatalln(err) 24 } 25 msg := fmt.Sprintf("insert successful %d", ra) 26 c.JSON(http.StatusOK, gin.H{ 27 "msg": msg, 28 }) 29 }
1 package main 2 3 import ( 4 "github.com/gin-gonic/gin" 5 . "aze.orgd/apis" 6 ) 7 8 func initRouter() *gin.Engine { 9 router := gin.Default() 10 11 router.GET("/", IndexApi) 12 13 router.POST("/person", AddPersonApi) 14 15 router.GET("/persons", GetPersonsApi) 16 17 router.GET("/person/:id", GetPersonApi) 18 19 router.PUT("/person/:id", ModPersonApi) 20 21 router.DELETE("/person/:id", DelPersonApi) 22 23 return router 24 }
package main import ( db "aze.org/database" ) func main() { defer db.SqlDB.Close() router := initRouter() router.Run(":8000") }
运行项目,
go run main.go router.go
或者
如果是最终编译二进制项目,则运行
go build -o app //生成app文件直接./app就可以运行项目了。
参考教程:
Gin框架 详细文档地址:https://godoc.org/github.com/gin-gonic/gin