gin example

This commit is contained in:
flybread 2025-06-17 16:10:25 +08:00
parent ee981f128a
commit 533d578ab5
10 changed files with 70 additions and 41 deletions

View File

@ -2,16 +2,31 @@ package main
import ( import (
"fmt" "fmt"
"net/http"
"time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/examples/url/ini" "github.com/gin-gonic/gin/examples/url/ini"
) )
func main() { func main() {
fmt.Println("h")
fmt.Println("Hello Gin") fmt.Println("Hello Gin")
// Force log's color
gin.ForceConsoleColor()
// disable log`s color
//gin.DisableConsoleColor()
router := gin.Default() router := gin.Default()
ini.UrlInit(router) ini.UrlInit(router)
err := router.Run(":8080") s := &http.Server{
Addr: ":8080",
Handler: router,
ReadTimeout: 10 * time.Second, // ReadTimeout
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
err := s.ListenAndServe()
if err != nil { if err != nil {
return return
} // listen and serve on 0.0.0.0:8080 }
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 KiB

View File

@ -9,11 +9,12 @@ import (
) )
//go:embed assets/* templates/* //go:embed assets/* templates/*
var f embed.FS var f embed.FS //web页面的存储的内容
func main() { func main() {
router := gin.Default() router := gin.Default()
templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl")) templ := template.Must(template.New("").
ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl"))
router.SetHTMLTemplate(templ) router.SetHTMLTemplate(templ)
// example: /public/assets/images/example.png // example: /public/assets/images/example.png

View File

@ -0,0 +1,5 @@
<html>
<h1>
{{ .title }}
</h1>
</html>

View File

@ -0,0 +1,5 @@
<html>
<h1>
{{ .title }}
</h1>
</html>

View File

@ -18,6 +18,12 @@ type Body struct {
EndDate1 time.Time `form:"end_date_1" binding:"required" time_format:"2006-01-02"` EndDate1 time.Time `form:"end_date_1" binding:"required" time_format:"2006-01-02"`
} }
type Person struct {
ID string `uri:"id" binding:"required"`
//ID string `uri:"id" binding:"required,uuid"`
Name string `uri:"name" binding:"required"`
}
func UrlInit(router *gin.Engine) { func UrlInit(router *gin.Engine) {
//普通url测试 //普通url测试
@ -119,43 +125,27 @@ func UrlInit(router *gin.Engine) {
c.JSON(http.StatusAccepted, &body) c.JSON(http.StatusAccepted, &body)
c.JSON(http.StatusAccepted, &body2) c.JSON(http.StatusAccepted, &body2)
}) })
}
type formB struct { router.GET("/:name/:id", func(c *gin.Context) {
Bar string `json:"bar" xml:"bar" binding:"required"` var person Person
} if err := c.ShouldBindUri(&person); err != nil {
c.JSON(400, gin.H{"msg": err.Error()})
return
}
c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID})
})
type formA struct { router.GET("/cookie", func(c *gin.Context) {
Foo string `json:"foo" xml:"foo" binding:"required"` cookie, err := c.Cookie("gin_cookie")
} if err != nil {
cookie = "NotSet"
func BindHandler(c *gin.Context) { c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)
objA := formA{} //Delete cookie by set max age to -1.
objB := formB{} //c.SetCookie("gin_cookie", "test", -1, "/", "localhost", false, true)
// This c.ShouldBind consumes c.Request.Body and it cannot be reused. }
if errA := c.ShouldBind(&objA); errA == nil { fmt.Printf("Cookie value: %s \n", cookie)
c.String(http.StatusOK, `the body should be formA`) c.JSON(http.StatusOK, gin.H{
// Always an error is occurred by this because c.Request.Body is EOF now. "cookie": cookie,
} else if errB := c.ShouldBind(&objB); errB == nil { })
c.String(http.StatusOK, `the body should be formB`) })
} else {
c.JSON(http.StatusOK, gin.H{"error": errA.Error()})
}
}
func MulBindHandler(c *gin.Context) {
objA := formA{}
objB := formB{}
// 读取 c.Request.Body 并将结果存入上下文。
if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil {
c.String(http.StatusOK, `the body should be formA`)
// 这时, 复用存储在上下文中的 body。
} else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {
c.String(http.StatusOK, `the body should be formB JSON`)
// 可以接受其他格式
} else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil {
c.String(http.StatusOK, `the body should be formB XML`)
} else {
c.JSON(http.StatusOK, gin.H{"error": errA.Error()})
}
} }

1
go.mod
View File

@ -7,6 +7,7 @@ require (
github.com/gin-contrib/sse v1.1.0 github.com/gin-contrib/sse v1.1.0
github.com/go-playground/validator/v10 v10.26.0 github.com/go-playground/validator/v10 v10.26.0
github.com/goccy/go-json v0.10.2 github.com/goccy/go-json v0.10.2
github.com/jessevdk/go-assets v0.0.0-20160921144138-4f4301a06e15
github.com/json-iterator/go v1.1.12 github.com/json-iterator/go v1.1.12
github.com/mattn/go-isatty v0.0.20 github.com/mattn/go-isatty v0.0.20
github.com/pelletier/go-toml/v2 v2.2.4 github.com/pelletier/go-toml/v2 v2.2.4

2
go.sum
View File

@ -38,6 +38,8 @@ github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 h1:yAJXTCF9TqKcTiHJAE8dj7HMvPfh66eeA2JYW7eFpSE= github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 h1:yAJXTCF9TqKcTiHJAE8dj7HMvPfh66eeA2JYW7eFpSE=
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/jessevdk/go-assets v0.0.0-20160921144138-4f4301a06e15 h1:cW/amwGEJK5MSKntPXRjX4dxs/nGxGT8gXKIsKFmHGc=
github.com/jessevdk/go-assets v0.0.0-20160921144138-4f4301a06e15/go.mod h1:Fdm/oWRW+CH8PRbLntksCNtmcCBximKPkVQYvmMl80k=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=

View File

@ -6,6 +6,8 @@ package gin
import ( import (
"encoding/xml" "encoding/xml"
"fmt"
"github.com/goccy/go-json"
"net/http" "net/http"
"os" "os"
"path" "path"
@ -162,3 +164,11 @@ func isASCII(s string) bool {
} }
return true return true
} }
func ToString(v interface{}) string {
bytes, err := json.Marshal(v)
if err != nil {
panic(fmt.Sprintf("json.Marshal err %+v", err))
}
return string(bytes)
}