Gin 프레임워크 사용해보기

POII·2022년 11월 7일
0

go_study

목록 보기
6/7
post-thumbnail

Gin이란?

Gin은 Go언어로 작성된 HTTP web 프레임워크이다. 기존에 go에서 사용되던 martini 라는 프레임워크에 비해 성능을 40배가까이 향상 시켰다고 한다.


간단한 예제로 Gin 프레임워크 기능 사용해보기

전달할 데이터 구조체로 만들기

// album represents data about a record album.
type album struct {
    ID     string  `json:"id"`
    Title  string  `json:"title"`
    Artist string  `json:"artist"`
    Price  float64 `json:"price"`
}

‘json:”전달할 이름”’ 을 변수 선언 뒤에 붙여주면, json으로 직렬화 할 때 필드의 이름을 직접 설정할 수 있다. 만약 이를 붙이지 않으면 구조체내에서 설정한 대문자 변수 명이 필드의 이름이 된다.

🌱 json 형태에서는 대문자 변수명을 일반적으로 사용하지 않는다.

GET 요청을 처리할 함수 만들기


// getAlbums responds with the list of all albums as JSON.
func 함수이름(c *gin.Context) {
    c.IndentedJSON(http.StatusOK, 전달할 구조체 or 구조체 배열)
}
  • 함수 이름은 사용자가 원하는대로 지정할 수 있다.
  • 함수의 인자 gin.Context는 request안의 정보를 가지고 있고, JSON을 검증 직렬화할때 사용합니다.
  • Context.IntendedJSON 메소드
    • 1번째 인자로 response의 HTTP의 상태코드를 전달한다.
    • 2번째 인자로 전달되는 데이터를 JSON 형태로 변환하여 response에 추가시킨다.

만든 함수를 URI에 매핑하기

func main() {
    router := gin.Default()
    router.GET("/albums", 함수이름)

    router.Run("localhost:8080")
}
  • router := gin.Default() 에서 Gin의 router를 Default로 초기화시킨다.
  • router.HTTP메소드이름 (”uri”, 함수이름)으로 http 메소드와 uri 에 맞게 요청을 처리 할 함수를 지정할 수 있다.
  • router.Run 함수는 httpServer에 router를 연결해주고 서버를 작동시킨다.

POST요청을 처리할 함수 만들기

// postAlbums adds an album from JSON received in the request body.
func 함수이름(c *gin.Context) {
    var newAlbum album

    // Call BindJSON to bind the received JSON to
    // newAlbum.
    if err := c.BindJSON(&newAlbum); err != nil {
        return
    }

    // Add the new album to the slice.
    albums = append(albums, newAlbum)
    c.IndentedJSON(http.StatusCreated, newAlbum)
}

...

func main() {
    router := gin.Default()
    router.POST("/albums", 함수이름)

    router.Run("localhost:8080")
}
  • BindJSON 함수는 인자로 준 주소에 request.body 를 bind 해준다.
  • IntendedJSON 함수로 이전과 같이 response에 담을 정보를 지정해준다.

파라미터가 있는 요청을 처리할 함수 만들기

// getAlbumByID locates the album whose ID value matches the id
// parameter sent by the client, then returns that album as a response.
func getAlbumByID(c *gin.Context) {
    id := c.Param("id")

    // Loop over the list of albums, looking for
    // an album whose ID value matches the parameter.
    for _, a := range albums {
        if a.ID == id {
            c.IndentedJSON(http.StatusOK, a)
            return
        }
    }
    c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}
  • Context.param(”키값”) 으로 키값에 해당하는 파라미터의 값을 얻어올 수 있다.
🌱 for _, a := range albums { … } 는 첫번째 인자로는 인덱스가 반환되므로 무시하고, 배열의 요소를 a에 하나씩 전달 받아 파라미터로 전달된 id값과 일치하는 id를 가진 요소가 있는지 검사한다.

reference:

https://go.dev/doc/tutorial/web-service-gin

profile
https://github.com/poi1649/learning

0개의 댓글