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

좋은 웹페이지 즐겨찾기