본문으로 바로가기

Go Gin 사용해보기

category Go 2022. 8. 16. 19:09
반응형

Go는 Go(Golang)으로 작성된 웹 프레임워크 입니다.

GitHub - gin-gonic/gin

 

GitHub - gin-gonic/gin: Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better perf

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin. - ...

github.com

 

Gin 설치

go get github.com/gin-gonic/gin

 

main.go

package main

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

func main() {
  router := gin.Default()
  router.GET("/ping", func(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{
      "message": "pong",
    })
  })
  router.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

 

실행

go run main.go

# localhost:8080/ping
# pong

 

소스 분석

 

Gin 엔진 생성

router := gin.Default()
//기본값은 Logger 및 Recovery 미들웨어가 이미 연결된 엔진 인스턴스를 반환합니다.
router := gin.Default()
//New는 Logger 및 Recovery 미들웨어가 연결되지 않은 새 빈 엔진 인스턴스를 반환합니다.
router := gin.New()

//Logger Custom
router.Use(gin.LoggerWithFormatter(func(params gin.LogFormatterParams) string {
    return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
        params.ClientIP,
        params.TimeStamp.Format(time.RFC1123),
        params.Method,
        params.Path,
        params.Request.Proto,
        params.StatusCode,
        params.Latency,
        params.Request.UserAgent(),
        params.ErrorMessage,
    )
}))
//::1 - [Fri, 19 Aug 2022 14:53:05 KST] "GET /v1/user HTTP/1.1 200 425.1µs "PostmanRuntime/7.28.3""

 

라우터 설정

router.GET("/ping", func(c *gin.Context) {
...
}
router.GET("/ping", handleFunc)

//Http Method
//GET localhost:8080/ping
//POST localhost:8080/ping
..
router.GET("/ping", handleFunc)
router.POST("/ping", handleFunc)
router.PUT("/ping", handleFunc)
router.DELETE("/ping", handleFunc)

//Router Group
//GET localhost:8080/v1/ping
//POST localhost:8080/v1/pong
v1 := router.Group("/v1")
{
    v1.GET("/ping", handleFunc)
    v1.POST("/pong", handleFunc)
}

//Redirect
router.GET("/redirect", func(c *gin.Context) {
    c.Redirect(http.StatusMovedPermanently, "http://localhost:8080")
})

//Param
router.GET("/user/:name", handleFunc)
//localhost:8080/user/guest
//localhost:8080/user/test
router.GET("/user/:name/*action", handleFunc)
//localhost:8080/user/guest/info
//localhost:8080/user/guest/info/age

 

핸들러 함수

func(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "pong",
	})
}
핸들러 함수 선언 방식
	1. 함수 선언
	2. 익명 함수 선언
	3. 인라인 선언
func main() {
	...
	
	v1 := router.Group("/v1")
	{
		// 함수 선언
		v1.GET("/user", getUser)
		v1.POST("/user", postUser)

		// 익명함수
		putUser := func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"message": "PUT",
			})
		}
		v1.PUT("/user", putUser)

		// 인라인 선언
		v1.DELETE("/user", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"message": "DELETE",
			})
		})
	}
	
	...
}

func getUser(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "GET",
	})
}

func postUser(c *gin.Context) {
	c.JSON(http.StatusCreated, gin.H{
		"message": "POST",
	})
}

 

URL Param, URL Query

v1.GET("/user/:id/*action", getUserAction)

func getUserAction(c *gin.Context) {
	//URL 파라미터
	id := c.Param("id")
	action := c.Param("action")

	//URL Query
	firstName := c.DefaultQuery("firstname", "Guest")
	lastName := c.Query("lastname")
	password, isInputed := c.GetQuery("password")

	c.JSON(http.StatusOK, gin.H{
		"message":   "GET",
		"id":        id,
		"action":    action,
		"firstName": firstName,
		"lastname":  lastName,
		"password":  password,
		"isInputed": isInputed,
	})
}

/*
localhost:8080/v1/user/testid/info/age?firstname=HONG&lastname=GILDONG&password=1234
{
    "action": "/info/age",
    "firstName": "HONG",
    "isInputed": true,
    "lastname": "GILDONG",
    "message": "GET",
    "name": "testid",
    "password": "1234"
}

localhost:8080/v1/user/testid/info/age?lastname=GILDONG&password=1234
{
    "action": "/info/age",
    "firstName": "Guest",
    "isInputed": true,
    "lastname": "GILDONG",
    "message": "GET",
    "name": "testid",
    "password": "1234"
}
*/

실행

router.Run()
// 포트 지정
r.Run(":8080")

// Custom
server := &http.Server{
	Addr:           ":8080",
	Handler:        router,
	ReadTimeout:    10 * time.Second,
	WriteTimeout:   10 * time.Second,
	MaxHeaderBytes: 1 << 20,
}
server.ListenAndServe()
반응형

'Go' 카테고리의 다른 글

Elasticsearch Golang Client 사용하기  (0) 2023.08.25
Golang RabbitMQ 클라이언트 사용해보기  (0) 2022.08.19
Golang 설치  (0) 2022.08.16