gin-web 框架

// ping
package main

import (
    "fmt"

    "net/http"

    "github.com/gin-gonic/gin"
)

func hello(c *gin.Context) {
    c.XML(200, gin.H{
        "message": "hey", "status": http.StatusOK,
    })
}

func main() {
    fmt.Println("Hello World!")

    r := gin.Default()
    // r.GET("/ping", func(c *gin.Context) {
    //  c.JSON(200, gin.H{
    //      "messge": "pong",
    //  })
    // })

    r.GET("/ping", hello)

    r.GET("/someJSON", func(c *gin.Context) {
        data := map[string]interface{}{
            "lang": "go",
            "tag":  "<br>",
        }
        c.AsciiJSON(http.StatusOK, data)
    })

    //------------

    r.Run(":8001")
}

突然有个贱想法:如果main类中使用两个端口会怎么样

// ping
package main

import (
    // "fmt"

    "net/http"

    "github.com/gin-gonic/gin"
)

func hello(c *gin.Context) {
    c.XML(200, gin.H{
        "message": "hey", "status": http.StatusOK,
    })
}

func main() {

    r := gin.Default()

    r1 := gin.Default()
    // r.GET("/ping", func(c *gin.Context) {
    //  c.JSON(200, gin.H{
    //      "messge": "pong",
    //  })
    // })

    r.GET("/ping", hello)

    r.GET("/someJSON", func(c *gin.Context) {
        data := map[string]interface{}{
            "lang": "go",
            "tag":  "<br>",
        }
        c.AsciiJSON(http.StatusOK, data)
    })

    r1.GET("/ping", hello)

    //------------
    r1.Run(":8002")

    r.Run(":8001")
}

查看控制台,发现只有8002端口启动成功后不再往下执行。


image.png

想法二:方法处理函数放到Run 下面会怎么样

// ping
package main

import (
    // "fmt"

    "net/http"

    "github.com/gin-gonic/gin"
)

func hello(c *gin.Context) {
    c.XML(200, gin.H{
        "message": "hey", "status": http.StatusOK,
    })
}

func main() {

    r := gin.Default()

    r1 := gin.Default()
    // r.GET("/ping", func(c *gin.Context) {
    //  c.JSON(200, gin.H{
    //      "messge": "pong",
    //  })
    // })

    r.GET("/ping", hello)

    r.GET("/someJSON", func(c *gin.Context) {
        data := map[string]interface{}{
            "lang": "go",
            "tag":  "<br>",
        }
        c.AsciiJSON(http.StatusOK, data)
    })

    // r1.GET("/ping", hello)

    //------------
    r1.Run(":8002")
    r1.GET("/ping", hello)
    r.Run(":8001")
}

结果:8082端口映射的ping 方法404了

image.png

Bind form-data request with custom struct

绑定对象

package main

import "github.com/gin-gonic/gin"

type StructA struct {
    FieldA string `form:"field_a"`
}

type StructB struct {
    NestedStruct StructA
    FieldB       string `form:"field_b"`
}

type StructC struct {
    NestedStructPointer *StructA
    FieldC              string `form:"field_c"`
}

type StructD struct {
    NestedAnonyStruct struct {
        FieldX string `form:""field_x`
    }
    FieldD string `form:"field_d"`
}

func GetDataB(c *gin.Context) {
    var b StructB
    c.Bind(&b)

    c.JSON(200, gin.H{"a": b.NestedStruct, "b": b.FieldB})
}

func GetDataC(c *gin.Context) {
    var b StructC
    c.Bind(&b)
    c.JSON(200, gin.H{"a": b.NestedStructPointer, "c": b.FieldC})
}

func GetDataD(c *gin.Context) {
    var b StructD
    c.Bind(&b)
    c.JSON(200, gin.H{"x": b.NestedAnonyStruct, "d": b.FieldD})
}

func main() {
    r := gin.Default()
    r.GET("/getb", GetDataB)
    r.GET("/getc", GetDataC)
    r.GET("/getd", GetDataD)

    r.Run()
}

测试 第一个正常参数,二三测试参数有多或者有不对应的,均未出现程序异常,参数接受异常处理做的挺好。

curl http://localhost:8080/getb?field_a=hello&field_b=world&field_c=22
curl http://localhost:8080/getb?field_a=hello&field_b=world
curl http://localhost:8080/getb?field_ab=hello&field_b=world&field_c=22

bind query string or post data

package main

import (
    "fmt"
    "log"
    "time"

    "github.com/gin-gonic/gin"
)

type Person struct {
    Name     string    `form:"name"`
    Address  string    `form:"address"`
    Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`
}

func main() {
    route := gin.Default()
    route.Any("/testing", startPage)
    route.Run(":8085")
}

func startPage(c *gin.Context) {
    var person Person
    // If `GET`, only `Form` binding engine (`query`) used.
    // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).
    // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48
    if c.ShouldBind(&person) == nil {
        fmt.Println("----")
        log.Println(person.Name)
        log.Println(person.Address)
        log.Println(person.Birthday)
    }

    c.String(200, "Success")
}
// $ curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15"

bing uri

package main

import "github.com/gin-gonic/gin"

type Person struct {
    ID   string `uri:"id" binding:"required,uuid"`
    Name string `uri:"name" binding:"required"`
}

func main() {
    route := gin.Default()
    route.GET("/:name/:id", func(c *gin.Context) {
        var person Person
        if err := c.ShouldBindUri(&person); err != nil {
            c.JSON(400, gin.H{"msg": err})
            return
        }
        c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID})
    })

    route.Run(":8000")
    /*
    $ curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3
    $ curl -v localhost:8088/thinkerou/not-uuid
    */
}

buid the third-party package

package main

//go get github.com/jessevdk/go-assets-builder
import (
    "html/template"
    "io/ioutil"
    "net/http"
    "strings"

    "github.com/gin-gonic/gin"
    // "github.com/jessevdk/go-assets"
)

func main() {
    r := gin.New()

    t, err := loadTemplate()
    if err != nil {
        panic(err)
    }
    r.SetHTMLTemplate(t)

    r.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "/html/index.tmpl", nil)
    })
    r.Run(":8080")
}

// loadTemplate loads templates embedded by go-assets-builder
func loadTemplate() (*template.Template, error) {
    t := template.New("")
    for name, file := range Assets.Files {
        if file.IsDir() || !strings.HasSuffix(name, ".tmpl") {
            continue
        }
        h, err := ioutil.ReadAll(file)
        if err != nil {
            return nil, err
        }
        t, err = t.New(name).Parse(string(h))
        if err != nil {
            return nil, err
        }
    }
    return t, nil
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容