Gin

Iris、Gin、Beego

Gin简介

https://gin-gonic.com/

Gin特点和特性

Gin环境搭建

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 工具创建项目

1.go get govendor

$ go get github.com/kardianos/govendor

2.创建项目并且 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请求和参数解析

通用处理

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

请求数据绑定和多数据格式处理

表单实体绑定

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


多数据格式返回请求结果

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

    //静态文件,设置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() //相当于服务器引擎

    //静态文件,设置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()

}

加载静态文件

<div align="center"><img src="../img/123.jpg"></div>
//加载静态资源文件
    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")
}





最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,635评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,543评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,083评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,640评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,640评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,262评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,833评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,736评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,280评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,369评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,503评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,185评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,870评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,340评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,460评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,909评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,512评论 2 359

推荐阅读更多精彩内容