GO: Gin Web Framework

GO: Gin Web Framework (Restful API)

go ์–ธ์–ด๋ฅผ ์“ฐ๋Š” ๋งˆ์ดํฌ๋กœ ์›น ํ”„๋ ˆ์ž„์›Œํฌ์ด๋‹ค.



Quickstart

$ go mod init example/web-service-gin

go mod init ๋ช…๋ น์–ด๋ฅผ ํ†ตํ•ด ์ข…์†์„ฑ๊ด€๋ฆฌ์™€ ํŒจํ‚ค์ง€๋ฅผ ์„ค์น˜ํ•ฉ๋‹ˆ๋‹ค.


๊ตฌ์กฐ์ฒด ์„ ์–ธ

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},
}

์œ„์™€ ๊ฐ™์ด ๊ตฌ์กฐ์ฒด๋ฅผ ์„ ์–ธํ•˜๊ณ  ์„ ์–ธํ•œ ๊ตฌ์กฐ์ฒด์— ๋ฐ์ดํ„ฐ๋ฅผ ๋„ฃ๋Š”๋‹ค.

๊ตฌ์กฐ์ฒด์˜ ํ•„๋“œ ๋์— ์—ญ๋”ฐ์˜ดํ‘œ๊ฐ€ ๋ถ™๋Š” ์ด์œ :
Raw string์€ ๋ณดํ†ต JSON ํ˜•์‹์˜ String์„ ์ฒ˜๋ฆฌํ•  ๋•Œ ์ข…์ข… ์‚ฌ์šฉํ•œ๋‹ค. JSON key, value๊ฐ€ ์ผ๋ฐ˜์ ์œผ๋กœ ์Œ๋”ฐ์˜ดํ‘œ๋กœ ์ด๋ฃจ์–ด์ง„ string์ด๊ธฐ ๋•Œ๋ฌธ์— ์ด๋ฅผ Interpreted string์œผ๋กœ ๋‚˜ํƒ€๋‚ด๊ฒŒ ๋˜๋ฉด ์Œ๋”ฐ์˜ดํ‘œ ๊ตฌ๋ถ„์„ ๋ช…ํ™•ํ•˜๊ฒŒ ํ•ด์ค˜์•ผ ํ•ด์„œ ๋ฒˆ๊ฑฐ๋กญ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ***

ํ•จ์ˆ˜

ํŒŒ์ผ๋์— ํ•จ์ˆ˜๋ฅผ ์„ ์–ธํ•˜๋Š”๊ฒŒ ์ข‹์ง€๋งŒ Go๋Š” ์–ด๋””์— ์œ„์น˜ํ•ด๋„ ์ƒ๊ด€์—†๋‹ค. ###

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

gin.Context : json์˜ ์œ ํšจ์„ฑ์„ ๊ฒ€์‚ฌํ•˜๊ณ  ์ง๋ ฌํ™”๋ฅผ ๋‹ด๋‹น
Context.IndentedJSON: json์„ ์ง๋ ฌํ™”ํ•˜๊ณ  ์‘๋‹ต์„ ์ถ”๊ฐ€ํ•˜๊ธฐ ์œ„ํ•ด์„œ ์“ด๋‹ค
</br>

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

	if err := c.BindJSON(&newAlbum); err != nil {
		return
	}

	albums = append(albums, newAlbum)
	c.IndentedJSON(http.StatusCreated, newAlbum)
}

Context.BindJSON: request body ๋ฅผ newAlbum ๋ณ€์ˆ˜์— ๋งตํ•‘


</br>

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."})
}

Context.Param: URL ๋กœ ๋ถ€ํ„ฐ id path parameter์„ ์ถ”์ถœ ***

main ํ•จ์ˆ˜


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

	router.Run("localhost:8080")
}

Default: Gin์—์„œ ๊ธฐ๋ณธ์ ์ธ ๋ผ์šฐํ„ฐ๋ฅผ ์ƒ์„ฑ


๊ฒฐ๊ณผ

image

image

image image

Categories:

Updated:

Leave a comment