1. gin 기초
10022 단어 Golang
1.
1.
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/get", func(c *gin.Context) {
c.String(200,"get")
})
r.POST("/post", func(c *gin.Context) {
c.String(200,"post")
})
r.Handle("DELETE","delete", func(c *gin.Context) {
c.String(200,"delete")
})
r.Any("/any", func(c *gin.Context) {
c.String(200,"any")
})
r.Run()
}
2.
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
//
r.Static("/asset", "./asset")
r.StaticFS("/static",http.Dir("static"))
//
r.StaticFile("/favicon.ico","./favicon.ico")
r.Run()
}
3. url
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/:name/:id", func(c *gin.Context) {
c.JSON(200,gin.H{
"name":c.Param("name"),
"id":c.Param("id"),
})
})
r.Run()
}
4.
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/user/*action", func(c *gin.Context) {
c.String(200,"hello,world")
})
r.Run()
}
2.
1. get
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/test", func(c *gin.Context) {
firstName := c.Query("first_name")
lastName := c.DefaultQuery("last_name","last_default_name")
c.String(http.StatusOK,"%s,%s",firstName,lastName)
})
r.Run()
}
2. post
package main
import (
"github.com/gin-gonic/gin"
"io/ioutil"
"net/http"
)
func main() {
//curl -X POST "http://127.0.0.1:8080/test" -d '{"name":"wang"}'
r := gin.Default()
r.POST("/test", func(c *gin.Context) {
bodyBytes, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
c.String(http.StatusBadRequest,err.Error())
c.Abort()
}
c.String(http.StatusOK, string(bodyBytes))
})
r.Run(":8080")
}
3. body
package main
import (
"github.com/gin-gonic/gin"
"io/ioutil"
"net/http"
"bytes"
)
func main() {
//curl -X POST "http://127.0.0.1:8080/test" -d '{"name":"wang"}'
r := gin.Default()
r.POST("/test", func(c *gin.Context) {
// ReadAll,PostForm
bodyBytes, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
c.String(http.StatusBadRequest,err.Error())
c.Abort()
}
// body
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
firstName := c.PostForm("first_name")
lastName := c.PostForm("last_name")
c.String(http.StatusOK, "%s --- %s --- %s",firstName,lastName,string(bodyBytes))
})
r.Run(":8080")
}
4.
package main
import (
"github.com/gin-gonic/gin"
"time"
)
type Person struct {
Name string `form:"name"`
Address string `form:"address"`
Birthday time.Time `form:"birthday" time_format:"2006-01-02"`
}
func main() {
r := gin.Default()
r.GET("/testing", testing)
r.POST("/testing",testing)
r.Run()
}
//curl -X GET "http://127.0.0.1:8080/testing?name=wei"
//curl -X GET "http://127.0.0.1:8080/testing?name=wei&address=shanghai"
//curl -X GET "http://127.0.0.1:8080/testing?name=wei&address=shanghai&birthday=2020-01-01"
//curl -X POST "http://127.0.0.1:8080/testing" -d 'name=test&address=beijing&birthday=2000-01-02'
//curl -H "Content-Type:application/json" -X POST "http://127.0.0.1:8080/testing" -d '{"name":"huang"}'
func testing(c *gin.Context) {
var person Person
// content-type binding
if err := c.ShouldBind(&person); err == nil {
c.String(200,"%v",person)
} else {
c.String(200,"person bind error : %v",err)
}
}
3.
1.
package main
import "github.com/gin-gonic/gin"
type Person struct {
Age int `form:"age" binding:"required,gt=10"`
Name string `form:"name" binding:"required"`
Address string `form:"address" binding:"required"`
}
// curl -X GET "http://127.0.0.1:8080/testing?age=18&name=wei&address=wuhan"
func main() {
r := gin.Default()
r.GET("/testing", func(c *gin.Context) {
var person Person
if err := c.ShouldBind(&person); err != nil {
c.String(500,"%v",err)
}
c.String(200,"%v",person)
})
r.Run()
}
2.
package main
import (
"github.com/gin-gonic/gin"
"time"
"github.com/go-playground/validator"
"github.com/gin-gonic/gin/binding"
)
type Booking struct {
CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-02-02"`
CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-02-02"`
}
//curl -X GET "http://127.0.0.1:8080/bookable?check_in=2019-07-22&checkout_out=2019-07-22"
func main() {
r := gin.Default()
if v,ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("bookabledate",bookableDate)
}
r.GET("/bookable", func(c *gin.Context) {
var b Booking
if err := c.ShouldBind(b); err != nil {
c.JSON(500,gin.H{"error":err.Error()})
return
}
c.JSON(200,gin.H{"message":"ok","booking":b})
})
r.Run()
}
var bookableDate validator.Func = func(fl validator.FieldLevel) bool {
date, ok := fl.Field().Interface().(time.Time)
if ok {
today := time.Now()
if today.After(date) {
return false
}
}
return true
}
https://github.com/gin-gonic/gin#custom-validators
3. ---
package main
import (
"time"
"github.com/go-playground/validator"
"github.com/go-playground/universal-translator"
en2 "github.com/go-playground/locales/en"
zh2 "github.com/go-playground/locales/zh"
"github.com/gin-gonic/gin"
"golang.org/x/sys/unix"
zh_translations "gopkg.in/go-playground/validator.v9/translations/zh"
en_translations "gopkg.in/go-playground/validator.v9/translations/en"
)
type Person struct {
// binding validate v9
Age int `form:"age" validate:"required,gt=10"`
Name string `form:"name" validate:"required"`
Address string `form:"address" validate:"required"'`
}
var (
Uni *ut.UniversalTranslator
Validate *validator.Validate
)
//curl -X GET "http://127.0.0.1:8080/testing?name=wang&age=11&locale=en"
func main() {
//
Validate = Validate.New()
zh := zh2.New()
en := en2.New()
//
Uni := ut.New(zh,en)
r := gin.Default()
r.GET("/testing", func(c *gin.Context) {
//
locale := c.DefaultQuery("locale","zh")
trans, _ := unix.Getdirentries("locale")
switch locale {
case "zh" :
zh_translations.RegisterDefaultTranslatioins(Validate,trans)
case "en" :
en_translations.RegisterDefaultTranslatioins(Validate,trans)
default:
zh_translations.RegisterDefaultTranslatioins(Validate,trans)
}
var person Person
// shouldbind
if err := c.ShouldBind(&person); err != nil {
c.String(500,"%v",err)
c.Abort()
return
}
// validate
if err := Validate.Struct(person); err != nil {
// ,
errs := err.(validator.ValidationErrors)
sliceErrs := []string{}
for _, e := range errs {
sliceErrs = append(sliceErrs, e.Translate(trans))
}
c.String(500, "%v", sliceErrs)
c.Abort()
return
}
c.String(200,"%v",person)
})
r.Run()
}
4.
1. gin
package main
import (
"github.com/gin-gonic/gin"
"os"
"io"
)
//curl -X GET "http://127.0.0.1:8080/test"
func main() {
//
f,_ := os.Create("gin.log")
gin.DefaultWriter = io.MultiWriter(f)
//
gin.DefaultErrorWriter = io.MultiWriter(f)
r := gin.New()
// panic
r.Use(gin.Logger(), gin.Recovery())
r.GET("/test", func(c *gin.Context) {
name := c.DefaultQuery("name", "default_name")
panic("test panic")
c.String(200,"%s",name)
})
r.Run()
}
2.
package main
import "github.com/gin-gonic/gin"
func IPAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
ipList := []string {
"127.0.0.2",
}
flag := false
clientIP := c.ClientIP()
for _, host := range ipList {
if clientIP == host {
flag = true
break
}
}
if !flag {
c.String(401, "%s, not in iplist",clientIP)
c.Abort()
}
}
}
func main() {
r := gin.Default()
r.Use(IPAuthMiddleware())
r.GET("/test", func(c *gin.Context) {
c.String(200,"hello test")
})
r.Run()
}
5.
1.
package main
import (
"github.com/gin-gonic/gin"
"net/http"
"log"
"os"
"os/signal"
"syscall"
"context"
"time"
)
// curl -X GET "http://127.0.0.1:8080/test"
func main() {
r := gin.Default()
r.GET("/test", func(c *gin.Context) {
time.Sleep(10 * time.Second)
c.String(200,"hello,test")
})
srv := &http.Server{
Addr:":8080",
Handler:r,
}
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s
",err)
}
}()
quit := make(chan os.Signal)
signal.Notify(quit, syscall.SIGINT, syscall.SIGQUIT)
https://github.com/e421083458/gin_scaffold
https://www.jianshu.com/p/a31e4ee25305
https://www.yoytang.com/go-gin-doc.html
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Golang 구현 대기열 및 스택대기열: 스택: github 주소:https://github.com/golibec/Lstruct.git 후속적으로 각종 데이터 구조와 주류 알고리즘을 지속적으로 보완할 것이다....
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.