gin-gonic으로 RESTful API 개발하기 (2)

Melon Coder·2024년 7월 9일

Go

목록 보기
13/14

gin-gonic으로 RESTful API 개발하기 (1) 에서는 GET 을 통해 통신하는 방법을 소개했다.

이번에는 기존 데이터에 새로운 데이터를 추가하는 방식인 POST 요청에 대해 알아본다.

POST

func postPlayer(c *gin.Context) {
	var newPlayer player

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

	players = append(players, newPlayer)
	c.IndentedJSON(http.StatusCreated, newPlayer)
}

위와 같이 코드를 작성해주고 나면 HTTP POST 요청을 보낼 수 있다.

한 줄씩 코드 설명을 해보면,

var newPlayer player
-> player 타입의 데이터 저장을 위한 변수 선언

if err := c.BindJSON(&newPlayer); err != nil { return }
-> 요청의 json 형식의 데이터를 읽고 newPlayer 변수에 바인딩(매핑)한다.
본문이 JSON 형식이 아니거나 구조체에 매핑하지 못할 경우 에러를 리턴한다.

players = append(players, newPlayer)
-> players 슬라이스에 newPlayer를 추가한다.

c.IndentedJSON(http.StatusCreated, newPlayer)
-> HTTP 상태 코드 201(Created)과 함께 새로 추가된 데이터를 JSON 형식으로 클라이언트에게 응답한다.

profile
create new things

0개의 댓글