[go] gin 프레임

gin 참조
Gin 프레임 반환 값
//   json

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

    //   :     json
    // gin.H is a shortcut for map[string]interface{}
    r.GET("/someJSON", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
    })
    
    //  2:        
    r.GET("/moreJSON", func(c *gin.Context) { // You also can use a struct
        var msg struct {
            Name    string `json:"user"`
            Message string
            Number  int
        }
        msg.Name = "Lena"
        msg.Message = "hey"
        msg.Number = 123
        
        // Note that msg.Name becomes "user" in the JSON
        c.JSON(http.StatusOK, msg)
    })

    // Listen and serve on 0.0.0.0:8080
    r.Run(":8080")
}
//   html

router.LoadHTMLGlob("templates/*")
router.Static("/static", "./static") 

func main() {
    router := gin.Default()

    router.LoadHTMLGlob("templates/*")  // LoadHTMLFiles        
    router.Static("/static", "./static") //            

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

Gin 프레임 매개 변수 전달
//     querystring

/user/search?name=mm&age=22

r.GET("/user/search", func(c *gin.Context)
name := c.DefaultQuery("name", "mm") //     
name := c.Query("name")

func main() {
    r := gin.Default()
    r.GET("/user/search", func(c *gin.Context) {
        name := c.DefaultQuery("name", "mm")
        //name := c.Query("name")
        age := c.Query("age")

        //  json      
        c.JSON(200, gin.H{
            "message":  "pong",
            "name": name,
            "age":  age,
        })
    })

    r.Run() // listen and serve on 0.0.0.0:8080
}
//      path

/user/search/mm/22
r.GET("/user/search/:name/:age", func(c *gin.Context) 

name := c.Param("mm")

func main() {
    r := gin.Default()
    r.GET("/user/search/:name/:age", func(c *gin.Context) {
        name := c.Param("mm")
        age := c.Param("age")

        //  json      
        c.JSON(200, gin.H{
            "message":  "pong",
            "username": username,
            "address":  address,
        })
    })

    r.Run(":8080") // listen and serve on 0.0.0.0:8080
}
//     : form  

r.POST("/user/search", func(c *gin.Context) {
name := c.DefaultPostForm("name", "mm")
name := c.PostForm("name")

func main() {
    r := gin.Default()
    r.POST("/user/search", func(c *gin.Context) {
        //name := c.DefaultPostForm("name", "mm")
        name := c.PostForm("name")
        age := c.PostForm("age")
        //  json      
        c.JSON(200, gin.H{
            "message":  "pong",
            "name": name,
            "age":  age,
        })
    })

    r.Run(":8080")
}

// Binding from JSON
type Login struct {
    User     string `form:"user" json:"user" binding:"required"`
    Password string `form:"password" json:"password" binding:"required"`
}

func main() {
    router := gin.Default()

    // Example for binding JSON ({"user": "manu", "password": "123"})
    router.POST("/loginJSON", func(c *gin.Context) {
        var login Login

        if err := c.ShouldBindJSON(&login); err == nil {
            fmt.Printf("login info:%#v
", login) c.JSON(http.StatusOK, gin.H{ "user": login.User, "password": login.Password, }) } else { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } }) // Example for binding a HTML form (user=manu&password=123) router.POST("/loginForm", func(c *gin.Context) { var login Login // This will infer what binder to use depending on the content-type header. if err := c.ShouldBind(&login); err == nil { c.JSON(http.StatusOK, gin.H{ "user": login.User, "password": login.Password, }) } else { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } }) // Example for binding a HTML querystring (user=manu&password=123) router.GET("/loginForm", func(c *gin.Context) { var login Login // This will infer what binder to use depending on the content-type header. if err := c.ShouldBind(&login); err == nil { c.JSON(http.StatusOK, gin.H{ "user": login.User, "password": login.Password, }) } else { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } }) // Listen and serve on 0.0.0.0:8080 router.Run(":8080") }

gin Restful
// restful  

func main() {
    //Default           
    r := gin.Default()
    r.GET("/user/info", func(c *gin.Context) {
        //  json      
        c.JSON(200, gin.H{
            "message": "get user info succ",
        })
    })
    r.POST("/user/info", func(c *gin.Context) {
        //  json      
        c.JSON(200, gin.H{
            "message": "create user info succ",
        })
    })
    r.PUT("/user/info", func(c *gin.Context) {
        //  json      
        c.JSON(200, gin.H{
            "message": "update user info succ",
        })
    })
    r.DELETE("/user/info", func(c *gin.Context) {
        //  json      
        c.JSON(200, gin.H{
            "message": "delete user info succ ",
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}
//     

func login(ctx *gin.Context) {
    ctx.JSON(200, gin.H{
        "message": "success",
    })
}

func read(ctx *gin.Context) {
    ctx.JSON(200, gin.H{
        "message": "success",
    })
}

func submit(ctx *gin.Context) {
    ctx.JSON(200, gin.H{
        "message": "success",
    })
}

func main() {
    //Default           
    router := gin.Default()

    // Simple group: v1
    //   /v1/login
    //   /v1/submit
    //   /v1/read
    v1 := router.Group("/v1")
    {
        v1.POST("/login", login)
        v1.POST("/submit", submit)
        v1.POST("/read", read)
    }

    // Simple group: v2
    //   /v2/login
    //   /v2/submit
    //   /v2/read
    v2 := router.Group("/v2")
    {
        v2.POST("/login", login)
        v2.POST("/submit", submit)
        v2.POST("/read", read)
    }

    router.Run(":8080")
}

Gin 미들웨어
//      

func StatCost() gin.HandlerFunc {
    return func(c *gin.Context) {
        t := time.Now()

        //          
        c.Set("example", "12345")
        //         
        c.Next()
        //    
        latency := time.Since(t)
        log.Printf("total cost time:%d us", latency/1000)
    }
}

func main() {
    //r := gin.New()
    r := gin.Default()
    r.Use(StatCost())

    r.GET("/test", func(c *gin.Context) {
        example := c.MustGet("example").(string)

        // it would print: "12345"
        log.Println(example)
        c.JSON(http.StatusOK, gin.H{
            "message": "success",
        })
    })

    // Listen and serve on 0.0.0.0:8080
    r.Run()
}
//         

func main() {
    router := gin.Default()
    router.GET("/someDataFromReader", func(c *gin.Context) {
        response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")
        if err != nil || response.StatusCode != http.StatusOK {
            c.Status(http.StatusServiceUnavailable)
            return
        }

        reader := response.Body
        contentLength := response.ContentLength
        contentType := response.Header.Get("Content-Type")

        extraHeaders := map[string]string{
            "Content-Disposition": `attachment; filename="gopher.png"`,
        }

        c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)
    })
    router.Run(":8080")
}

Gin 로그 쓰기
//      

func main() {
    // Disable Console Color, you don't need console color when writing the logs to file.
    gin.DisableConsoleColor()
    
    // Logging to a file.
    f, _ := os.Create("/tmp/gin.log")

    gin.DefaultWriter = io.MultiWriter(f)
    
    // Use the following code if you need to write the logs to file and console at the same time.
    // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
    //Default           
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        //  json      
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    
    r.Run() // listen and serve on 0.0.0.0:8080
}
//        

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

    // LoggerWithFormatter           gin.DefaultWriter
    // By default gin.DefaultWriter = os.Stdout
    router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {

        //        
        return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"
", param.ClientIP, param.TimeStamp.Format(time.RFC1123), param.Method, param.Path, param.Request.Proto, param.StatusCode, param.Latency, param.Request.UserAgent(), param.ErrorMessage, ) })) router.Use(gin.Recovery()) router.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) router.Run(":8080") }

좋은 웹페이지 즐겨찾기