Gin

作者: isuntong | 来源:发表于2020-03-27 14:16 被阅读0次

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

    相关文章

      网友评论

          本文标题:Gin

          本文链接:https://www.haomeiwen.com/subject/scokuhtx.html