@ (sample notebook) [Ma Kefei like help | | Markdown]

GIN API Framework is an API Framework built specifically for the Go GIN Framework. It incorporates the following components: Memcache Consistance Hash, Redis, NSQ, API Doc, Mysql, etc. Features overview:

  • Rich features: support most server components, support API Doc;
  • Handy: Simple examples that are very easy to learn;
  • Deep integration: deep integration of memcache, Redis, mysql, Beego, gin frameworks.
  • Performance first: why not use Beego? Gin is the most efficient and resource-intensive framework for Httprouter, while Beego ORm is the closest to Django. .

[TOC]

Begin to use

Perform the service
$ go run main.go
Copy the code
Generating documentation
$ go run gen_doc.go 
Copy the code
Synchronizing database model
$ go run orm_sync.go orm syncdb
Copy the code

Environment configuration

Deploy the service
  • Go Version go1.6.3 (golang.org) Over the Wall
  • godep ( github.com/tools/godep)
  • cd Gin_API_Framework/ && godep restore
Perform the service
$go run main. Go $open http://127.0.0.1:8080/docCopy the code

Frame structure

API directory structure

  • Controllers: Indicates the API code
  • Routers: API routing configuration code
  • Middleware: Middleware code
  • Docs: Generates API documentation code

Public directory

  • Utils: Common method code
  • Vendor: Godep save generates the dependent code
  • Background: back-end timing/asynchronous service code
  • Models: ORM data model code
  • Static: static file code

Web directory structure

  • Web-controllers [code]
  • Web-routers [HTTP Routing Configuration]
  • conf [beego config file]

The code block

// @title User Query By ID // @api_group User // @description Query User interface By User ID // @success 200 {object} // @param uid Query string false "user id" // @Failure 400 no enough input // @Failure 500 get common error // @router /user/query [get] func UserQueryByIdHandler(c *gin.Context) { suid := c.Query("uid") uid , error := strconv.Atoi(suid) if error ! = nil { c.JSON(400, gin.H{ "status": "fail", "msg": "String conversion to integer failed ",}) return} u := user.userQueryById (uid) c.son (http.statusok, gin.H {"status": "success", "user": u, }) }Copy the code

The ORM layer

func UserList() (users []User) {

    o := orm.NewOrm()
    qs := o.QueryTable("user")

    var us []User
    cnt, err :=  qs.Filter("id__gt", 0).OrderBy("-id").Limit(10, 0).All(&us)
    if err == nil {
        fmt.Printf("count", cnt)
        for _, u := range us {
            fmt.Println(u)
        }
    }
    return us
}

Copy the code

Cache configuration

inmem_store := cache.NewInMemoryStore(time.Second)
memcached_store := cache.NewMemcachedStore([]string{"localhost:11211"},time.Minute * 5)

v1.GET("/list",  cache.CachePage(inmem_store, time.Minute * 5 ,controllers.UserListHandler))
Copy the code

Middleware configuration

router.Use(nice.Recovery(recoveryHandler))

func recoveryHandler(c *gin.Context, err interface{}) {
    c.JSON(400,  gin.H{
        "status": "fail",
        "err":   err,
    })
}
Copy the code

go pprof debug

Ginpprof. Wrapper (router)} go to http://127.0.0.1:8080/debug/pprof/Copy the code

go Async Queue Message by Redis

package main import ( "Gin_API_Framework/utils/redis_model" _"encoding/json" "log" ) func sync_hello(dic map[string]interface{}) { log.Println("[sync_hello]..." ) log.Println("[recive dict]",dic) for key,value:=range dic { log.Println(key,value) } } func aysnc_do(queue *redis_model.RedisQueue) { value := map[string]interface{}{} value["hello"] = 1 value["world"] = 2 queue.ASync(value) } func main(){ queue := redis_model.NewRedisQueue("channel.test") aysnc_do(queue) //queue do work queue.Do(sync_hello) }Copy the code

Profile

API goroutine monitor profile
https://github.com/DeanThompson/ginpprof
Copy the code

API response time

The default is microseconds

run_api

The Web backend is constructed using beego framework

Service display

Start the service

$ go run web_main.go

Directory framework structure
  • Web-controllers [code]
  • Web-routers [HTTP Routing Configuration]
  • conf [beego config file]
  • Other directories such as Models are public
View Controller to build
type MainController struct {
    beego.Controller
}

func (this *MainController) Get() {
    this.TplName = "index.html"
    this.Layout = "layout/layout.html"
    this.Render()
}
Copy the code
Author: Hep