본문 바로가기
SW LAB/Go Lang

[Google Go 언어] Resultful API (Gin Web Framework)

by 프롬스 2021. 11. 15.
반응형
  • Gin Web Framework 를 이용하여 Restful API 구현
  • album 객체를 생성하고, 이 객체에 데이터를 추가하거나 조회하는 API 구현
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},
}

// 데이터 JSON 으로 변환하여 응답에 추가
func getAlbums(c *gin.Context) {
	// Json 을 직렬화 하고 응답에 추가하기 위해 호출
	c.IndentedJSON(http.StatusOK, albums)
}

// 지정된 ID의 데이터만 JSON 으로 변환하여 응답에 추가
func getAlbumByID(c *gin.Context) {
	id := c.Param("id")

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

// 데이터 수신 및 저장
func postAlbums(c *gin.Context) {
	var newAlbum album

	// newAlbum 으로 JSON to Object 변환
	if err := c.BindJSON(&newAlbum); err != nil {
		return
	}

	// albums 객체 배열에 객체 추가
	albums = append(albums, newAlbum)
	c.IndentedJSON(http.StatusCreated, newAlbum)
}

func main() {
	// gin Router 를 초기화
	router := gin.Default()
	// albums 경로와 메서드를 연결
	router.GET("/albums", getAlbums)
	router.GET("/albums/:id", getAlbumByID)
	router.POST("/albums", postAlbums)
	// 입력된 주소로 서버 시작
	router.Run("localhost:8080")
}
반응형

댓글