Gin

Iris、Gin、Beego

Gin簡介

https://gin-gonic.com/

Gin特點和特性

Gin環(huán)境搭建

1.下載并安裝 gin:
go get -u github.com/gin-gonic/gin

2.將 gin 引入到代碼中:
import "github.com/gin-gonic/gin"

3.(可選)如果使用諸如 http.StatusOK 之類的常量,則需要引入 net/http 包:
import "net/http"

使用 Govendor 工具創(chuàng)建項目

1.go get govendor

$ go get github.com/kardianos/govendor

2.創(chuàng)建項目并且 cd 到項目目錄中

$ mkdir -p $GOPATH/src/github.com/myusername/project && cd "$_"

3.使用 govendor 初始化項目,并且引入 gin

$ govendor init
$ govendor fetch github.com/gin-gonic/gin@v1.3

4.復(fù)制啟動文件模板到項目目錄中

$ curl https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go > main.go

5.啟動項目

$ go run main.go

開始

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "log"
)

func main() {

    engine := gin.Default() //相當(dāng)于服務(wù)器引擎
    engine.GET("/hello", func(context *gin.Context) { // *gin.Context : handlers
        fmt.Println("請求路徑:",context.FullPath())
        context.Writer.Write([]byte("hello gin\n"))
    })


    if err:=engine.Run(); err!= nil {
        log.Fatal(err.Error())
    }
}

修改端口:

if err:=engine.Run(":8090"); err!= nil {
        log.Fatal(err.Error())
    }

Http請求和參數(shù)解析

通用處理

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "log"
)

//2
func main() {

    /*
    使用handle通用處理
    */
    engine := gin.Default() //相當(dāng)于服務(wù)器引擎
    //http://localhost:8080/hello?name=isuntong
    engine.Handle("GET","/hello", func(context *gin.Context) {
        //context上下文封裝了很多常用的工具
        path := context.FullPath()
        fmt.Println(path)

        name := context.DefaultQuery("name","zhangsan")
        fmt.Println(name)

        //輸出
        context.Writer.Write([]byte("Hello " + name))
    })


    if err:=engine.Run(); err!= nil {
        log.Fatal(err.Error())
    }
}

post:

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "log"
)

//2
func main() {

    /*
    使用handle通用處理
    */
    engine := gin.Default() //相當(dāng)于服務(wù)器引擎
    //http://localhost:8080/hello?name=isuntong
    engine.Handle("GET","/hello", func(context *gin.Context) {
        //context上下文封裝了很多常用的工具
        path := context.FullPath()
        fmt.Println(path)

        name := context.DefaultQuery("name","zhangsan")
        fmt.Println(name)

        //輸出
        context.Writer.Write([]byte("Hello " + name))
    })

    //post
    //http://localhost:8080/login
    engine.Handle("POST","/login", func(context *gin.Context) {
        fmt.Println(context.FullPath())

        username := context.PostForm("username")
        password := context.PostForm("password")
        fmt.Println(username)
        fmt.Println(password)

        //輸出
        context.Writer.Write([]byte("Hello " + username))
    })


    if err:=engine.Run(); err!= nil {
        log.Fatal(err.Error())
    }
}

注意&分割

分類處理

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "log"
)

//3
func main() {

    /*
    分類處理
    */
    engine := gin.Default() //相當(dāng)于服務(wù)器引擎
    //http://localhost:8080/hello?name=isuntong
    engine.GET("/hello", func(context *gin.Context) {
        //context上下文封裝了很多常用的工具
        path := context.FullPath()
        fmt.Println(path)

        //無默認(rèn)值
        name := context.Query("name")
        fmt.Println(name)

        //輸出
        context.Writer.Write([]byte("Hello " + name))
    })


    //post
    //http://localhost:8080/login
    engine.POST("/login", func(context *gin.Context) {
        fmt.Println(context.FullPath())

        //能判斷是否包含
        username,exist := context.GetPostForm("username")
        if exist {
            fmt.Println(username)
        }
        password := context.PostForm("password")
        if exist {
            fmt.Println(password)
        }
        
        //輸出
        context.Writer.Write([]byte("Hello " + username))
    })


    //engine.Run()
    if err:=engine.Run(); err!= nil {
        log.Fatal(err.Error())
    }
}

engine.DELETE("/user/:id", func(context *gin.Context) {
        userID := context.Param("id")
        fmt.Println(userID)
        context.Writer.Write([]byte("delete " + userID))
    })

請求數(shù)據(jù)綁定和多數(shù)據(jù)格式處理

表單實體綁定

GET、POST 表單、POST json

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "log"
)

func main() {

    engine := gin.Default() //相當(dāng)于服務(wù)器引擎

    //http://localhost:8080/hello?name=isuntong&class=電信
    engine.GET("/hello", func(context *gin.Context) {
        fmt.Println(context.FullPath())

        var student Student
        err := context.ShouldBindQuery(&student)
        if err != nil {
            log.Fatal(err.Error())
        }

        fmt.Println(student.Name)
        fmt.Println(student.Class)

        context.Writer.Write([]byte("hello "+student.Name))

    })

    engine.Run()

}

type Student struct {
    //tig標(biāo)簽指定
    Name string `form:"name"`
    Class string `form:"class"`
}


post 表單

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "log"
)

//5
func main() {

    engine := gin.Default() //相當(dāng)于服務(wù)器引擎

    //http://localhost:8080/login
    engine.POST("/register", func(context *gin.Context) {

        fmt.Println(context.FullPath())

        var register Register
        if err:=context.ShouldBind(&register); err!=nil {
            log.Fatal(err.Error())
            return
        }
        fmt.Println(register.UserName)
        fmt.Println(register.Phone)

        context.Writer.Write([]byte(register.UserName + "Register!"))

    })

    engine.Run()

}

type Register struct {
    //tig標(biāo)簽指定
    UserName string `form:"name"`
    Phone string `form:"phone"`
    Password string `form:"password"`
}


post json

charles還是抓包工具
模擬請求還得搞一個postman

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "log"
)

//6
func main() {

    engine := gin.Default() //相當(dāng)于服務(wù)器引擎

    //http://localhost:8080/addstudent
    engine.POST("/addstudent", func(context *gin.Context) {

        fmt.Println(context.FullPath())

        var person Person

        if err:=context.BindJSON(&person); err!=nil {
            log.Fatal(err.Error())
            return
        }
        fmt.Println(person.Name)
        fmt.Println(person.Age)

        context.Writer.Write([]byte(person.Name + "add!"))

    })

    engine.Run()

}

type Person struct {
    //tig標(biāo)簽指定
    Name string `form:"name"`
    Sex string `form:"sex"`
    Age int `form:"age"`
}


多數(shù)據(jù)格式返回請求結(jié)果

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
)

//7
func main() {

    engine := gin.Default() //相當(dāng)于服務(wù)器引擎


    //http://localhost:8080/hellobyte
    engine.GET("/hellobyte", func(context *gin.Context) {
        fmt.Println(context.FullPath())

        context.Writer.Write([]byte("hellobyte"))

    })

    engine.GET("/hellostring", func(context *gin.Context) {
        fmt.Println(context.FullPath())

        context.Writer.WriteString("hellostring")

    })

    engine.Run()

}



json

//json map
    engine.GET("/hellojson", func(context *gin.Context) {
        fmt.Println(context.FullPath())

        context.JSON(http.StatusOK,map[string]interface{}{
            "code" : 1,
            "message" : "ok",
            "data" : context.FullPath(),
        })

    })
//json struct
    engine.GET("/hellojsonstruct", func(context *gin.Context) {
        fmt.Println(context.FullPath())


        resp := Response{1,"ok",context.FullPath()}
        context.JSON(http.StatusOK,&resp)

    })


    engine.Run()

}

type Response struct {
    Code int
    Message string
    Data interface{}
}

HTML

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)

//7
func main() {

    engine := gin.Default() //相當(dāng)于服務(wù)器引擎

    //靜態(tài)文件,設(shè)置html目錄
    engine.LoadHTMLGlob("./html/*")

    //http://localhost:8080/hellobyte
    engine.GET("/hellohtml", func(context *gin.Context) {
        fmt.Println(context.FullPath())

        context.HTML(http.StatusOK,"index.html",nil)

    })



    engine.Run()

}


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{.title}}</title>
</head>
<body>
hello html
{{.fullPath}}
</body>
</html>
package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)

//7
func main() {

    engine := gin.Default() //相當(dāng)于服務(wù)器引擎

    //靜態(tài)文件,設(shè)置html目錄
    engine.LoadHTMLGlob("./html/*")

    //http://localhost:8080/hellobyte
    engine.GET("/hellohtml", func(context *gin.Context) {
        fullPath := context.FullPath()
        fmt.Println(fullPath)

        context.HTML(http.StatusOK,"index.html",gin.H{
            "fullPath" : fullPath,
            "title" : "gin",
        })

    })



    engine.Run()

}

加載靜態(tài)文件

<div align="center"><img src="../img/123.jpg"></div>
//加載靜態(tài)資源文件
    engine.Static("/img","./img")

請求路由組的使用

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
)

//9
func main() {

    engine := gin.Default() //相當(dāng)于服務(wù)器引擎

    r := engine.Group("/user")

    //http://localhost:8080/user/hello
    r.GET("/hello", func(context *gin.Context) {
        fullPath := context.FullPath()
        fmt.Println(fullPath)

        context.Writer.WriteString("hello group")

    })


    r.GET("/hello2", hello2Handle)

    engine.Run()

}

func hello2Handle(context *gin.Context) {
    fullPath := context.FullPath()
    fmt.Println(fullPath)

    context.Writer.WriteString("hello2 group")
}





最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容