在Mac上安装 Go

由于我的环境是Mac ,直接下载 Pkg ,win 和 linux 下载地址都在这里 。Go安装包下载

#mac 直接安装安装包
go1.10.1.darwin-amd64.pkg

#将 go 路径添加到 profile  /usr/local/go/bin 
export  PATH = /usr/local/go/bin:$PATH 

source /etc/profile

leon:go leon$ go version
go version go1.10.1 darwin/amd64

安装 Gin

go get gopkg.in/gin-gonic/gin.v1

Ginhttp 路由用例

package main
import (
    "gopkg.in/gin-gonic/gin.v1"
    "net/http"
    "fmt"
)


func main(){
    // only set in Production
    // gin.SetMode(gin.ReleaseMode)  
    router := gin.Default()
    router.GET("/", func(c *gin.Context) {
        c.String(http.StatusOK, "Hello World,Welcome To Go~")
    })

    router.POST("/User", func(c *gin.Context) {
        c.String(http.StatusOK, "This is User Post MOdel~")
    })

    router.GET("/User", func(c *gin.Context) {
        c.String(http.StatusOK, "This is User MOdel~")
    })

    //url route with ':' to match 
    router.GET("/user/:name",func (c *gin.Context)  {
        name := c.Param("name")
        c.String(http.StatusOK,"Hello %s",name)
    })

    //URL route with '*' to match more 
    router.GET("/User/:name/*action",func (c *gin.Context){
        name:= c.Param("name")
        action := c.Param("action")
        message := name + "is" + action
        c.String(http.StatusOK,message)
    })


    // Restful-Get with qps 
    router.GET("/leon0204", func(c *gin.Context) {
        firstname := c.DefaultQuery("firstname", "Guest")
        lastname := c.Query("lastname")

        c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
    })

    // Restful-Post with qps 

    // res 
    /*
    {
        "message": "back from post",
        "nick": "默认Nickname",
        "status": {
            "status": "ok",
            "status_code": 200
        }
    }
    */

    router.POST("/leonPost",func (c *gin.Context)  {
        message:=c.PostForm("message")
        nick:= c.DefaultPostForm("nick","默认Nickname")

        c.JSON(http.StatusOK,gin.H {
            "status": gin.H{
                "status_code":http.StatusOK,
                "status": "ok",
            },
            "message":message,
            "nick":nick,
        })
    })

    // qps & urlParams  请求体和效果见下图
    router.PUT("/PostAll", func(c *gin.Context) {
        id := c.Query("id")
        page := c.DefaultQuery("page", "0")
        name := c.PostForm("name")
        message := c.PostForm("message")
        fmt.Printf("id: %s; page: %s; name: %s; message: %s \n", id, page, name, message)
        c.JSON(http.StatusOK, gin.H{
            "status_code": http.StatusOK,
        })
    })






    router.Run(":8005")
}

这里写图片描述

这里写图片描述

Logo

更多推荐