Gin+Mysql简单的Restful风格的API

数据库

CREATE TABLE `person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(40) NOT NULL DEFAULT '',
  `last_name` varchar(40) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

组织项目

在项目根目录创建下面三个文件夹,apis,databases和models,并在文件夹内创建文件。此时我们的目录结果如下:

myql.go的包代码如下:

package database

import (
 "database/sql"
 _ "github.com/go-sql-driver/mysql"
 "log"
)

var SqlDB *sql.DB

func 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())
 }
}

数据model封装

package models

import (
 "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

package apis

import (
 "net/http"
 "log"
 "fmt"
 "strconv"
 "gopkg.in/gin-gonic/gin.v1"
 . "newland/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,
 })
}

路由

package main

import (
 "gopkg.in/gin-gonic/gin.v1"
 . "newland/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入口

main.go

package main

import (
 db "newland/database"
)

func main() {
 defer db.SqlDB.Close()
 router := initRouter()
 router.Run(":8000")
}