GO언어 - Gin 프레임워크 활용하기

Gin 프레임워크 통한 API 구축

저번에는 Gin 프레임워크 초기 세팅을 해보았다. 이를 통해 API 구축을 진행해보겠다.

[참고 자료]

시작하기

GO언어에서 독립 실행형 프로그램(라이브러리와 반대)은 항상 package 에 main이 있다.
따라서 처음에 package main으로 시작해준다.

다음은 데이터베이스에 넣을 형태를 구축해준다.

type album struct {
    ID     string  `json:"id"`
    Title  string  `json:"title"`
    Artist string  `json:"artist"`
    Price  float64 `json:"price"`
}

필요한 데이터베이스에 넣을 데이터를 설정해준다.

var albums = []album{
    {ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
    {ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
    {ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}

API 함수를 작성하여 필요한 데이터를 얻는다. 데이터는 JSON형식으로 받는다.

func getAlbums(c *gin.Context) {
    c.IndentedJSON(http.StatusOK, albums)
}

url주소를 나누기 위해 해당 코드를 작성한다. 프론트엔드의 라우터느낌으로 봐도 좋다.
추가로 router group을 통해 원하는 주소를 더 작성할 수 있다.

func main() {
    router := gin.Default()
    router.GET("/albums", getAlbums)

    router.Run("localhost:8080")
}

아래는 공부한 내용을 바탕으로 최종적으로 정리하고 주석 넣은 파일이다.

package main

import (
	"net/http"

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

type album struct { // 주어진 형태(틀)
	ID     string  `json:"id"`
	Title  string  `json:"title"`
	Artist string  `json:"artist"`
	Price  float64 `json:"price"`
}

var albums = []album{ // 초기값 저장
	{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
	{ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
	{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}

func main() {
	router := gin.Default()
	v1 := router.Group("/v1") // v1으로 묶어서 라우팅 가능
	{
		v1.GET("/albums", getAlbums) // 각각 해당하는 함수 지정
		v1.GET("/albums/:id", getAlbumByID)
		v1.POST("/albums", postAlbums)
	}
	router.Run("localhost:8080")
}

func getAlbums(c *gin.Context) {
	c.IndentedJSON(http.StatusOK, albums)
}

func postAlbums(c *gin.Context) {
	var newAlbum album

	if err := c.BindJSON(&newAlbum); err != nil {
		return // 에러 발생시 출력
	}

	albums = append(albums, newAlbum) // 새로운 앨범을 추가 (append)
	c.IndentedJSON(http.StatusCreated, newAlbum)
}

func getAlbumByID(c *gin.Context) {
	id := c.Param("id")

	for _, a := range albums {
		if a.ID == id {
			c.IndentedJSON(http.StatusOK, a)
			return
		}
	}
	c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}

Categories:

Updated:

Comments