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.復制啟動文件模板到項目目錄中

$ 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() //相當于服務器引擎
    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() //相當于服務器引擎
    //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() //相當于服務器引擎
    //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() //相當于服務器引擎
    //http://localhost:8080/hello?name=isuntong
    engine.GET("/hello", func(context *gin.Context) {
        //context上下文封裝了很多常用的工具
        path := context.FullPath()
        fmt.Println(path)

        //無默認值
        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() //相當于服務器引擎

    //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標簽指定
    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() //相當于服務器引擎

    //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標簽指定
    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() //相當于服務器引擎

    //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標簽指定
    Name string `form:"name"`
    Sex string `form:"sex"`
    Age int `form:"age"`
}


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

package main

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

//7
func main() {

    engine := gin.Default() //相當于服務器引擎


    //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() //相當于服務器引擎

    //靜態(tài)文件,設置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() //相當于服務器引擎

    //靜態(tài)文件,設置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() //相當于服務器引擎

    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")
}





最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末烂斋,一起剝皮案震驚了整個濱河市础废,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌帘瞭,老刑警劉巖蝶念,帶你破解...
    沈念sama閱讀 218,682評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件媒殉,死亡現(xiàn)場離奇詭異摔敛,居然都是意外死亡,警方通過查閱死者的電腦和手機苦酱,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評論 3 395
  • 文/潘曉璐 我一進店門疫萤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來扯饶,“玉大人,你說我怎么就攤上這事钓丰∶勘遥” “怎么了兰怠?”我有些...
    開封第一講書人閱讀 165,083評論 0 355
  • 文/不壞的土叔 我叫張陵揭保,是天一觀的道長。 經常有香客問我存筏,道長味榛,這世上最難降的妖魔是什么搏色? 我笑而不...
    開封第一講書人閱讀 58,763評論 1 295
  • 正文 為了忘掉前任继榆,我火速辦了婚禮,結果婚禮上集币,老公的妹妹穿的比我還像新娘翠忠。我一直安慰自己秽之,他們只是感情好,可當我...
    茶點故事閱讀 67,785評論 6 392
  • 文/花漫 我一把揭開白布跨细。 她就那樣靜靜地躺著冀惭,像睡著了一般。 火紅的嫁衣襯著肌膚如雪媒楼。 梳的紋絲不亂的頭發(fā)上戚丸,一...
    開封第一講書人閱讀 51,624評論 1 305
  • 那天限府,我揣著相機與錄音,去河邊找鬼。 笑死牺弄,一個胖子當著我的面吹牛势告,可吹牛的內容都是我干的。 我是一名探鬼主播络拌,決...
    沈念sama閱讀 40,358評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼春贸,長吁一口氣:“原來是場噩夢啊……” “哼遗遵!你這毒婦竟也來了?” 一聲冷哼從身側響起允粤,我...
    開封第一講書人閱讀 39,261評論 0 276
  • 序言:老撾萬榮一對情侶失蹤类垫,失蹤者是張志新(化名)和其女友劉穎悉患,沒想到半個月后榆俺,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體跪削,經...
    沈念sama閱讀 45,722評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡碾盐,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年毫玖,在試婚紗的時候發(fā)現(xiàn)自己被綠了付枫。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片驰怎。...
    茶點故事閱讀 40,030評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡县忌,死狀恐怖,靈堂內的尸體忽然破棺而出装获,到底是詐尸還是另有隱情穴豫,我是刑警寧澤逼友,帶...
    沈念sama閱讀 35,737評論 5 346
  • 正文 年R本政府宣布帜乞,位于F島的核電站,受9級特大地震影響状植,放射性物質發(fā)生泄漏怨喘。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,360評論 3 330
  • 文/蒙蒙 一肉拓、第九天 我趴在偏房一處隱蔽的房頂上張望暖途。 院中可真熱鬧,春花似錦驻售、人聲如沸欺栗。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽臊泰。三九已至蚜枢,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間察滑,已是汗流浹背修肠。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評論 1 270
  • 我被黑心中介騙來泰國打工嵌施, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留莽鸭,地道東北人。 一個月前我還...
    沈念sama閱讀 48,237評論 3 371
  • 正文 我出身青樓足淆,卻偏偏與公主長得像巧号,于是被迫代替她去往敵國和親姥闭。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,976評論 2 355

推薦閱讀更多精彩內容