Springboot를 사용하면서 어노테이션을 너무 생각없이 사용하다 보니 HTTP 요청을 어떻게 처리하는지를 잘 모르고 넘겼었다. 그러다가 golang을 접하면서 Springboot와는 다른 방식으로 프레임워크를 사용하고, HTTP 요청 처리를 하면서 놓쳤던 부분들을 하나씩 알아가고 있는 중이다.😇
스프링부트 사용 시 @RequestBody 어노테이션을 사용하여 body를 자바 객체로 매핑
@PostMapping("/process")
public ResponseEntity<?> processRequest(@RequestBody ExampleDto requestBody) {
// requestBody를 사용하여 로직 수행
// ...
return ResponseEntity.ok("Success");
}
Gin에서는 body를 객체로 맵핑시키기 위해 두 가지 라이브러리 중 선택하여 사용할 수 있음
ShouldBindJSON은 객체로 변환 실패 시 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})와 같이 에러 발생 처리를 해줘야 함package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Login struct {
User string `json:"user" binding:"required"`
Password string `json:"password" binding:"required"`
}
func main() {
router := gin.Default()
router.POST("/login", func(c *gin.Context) {
var json Login
//json을 Login객체로 변환
if err := c.ShouldBindJSON(&json); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if json.User != "man" || json.Password != "123" {
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
return
}
c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
})
router.Run()
}
BindJSON 사용 시 객체로 변환하는 과정에서 에러가 발생하더라도 따로 에러 처리를 해 주지 않아도 됨BindJSON은 변환에 실패하면 Gin이 클라이언트에게 400 에러를 자동으로 응답package main
import (
"github.com/gin-gonic/gin"
)
type Login struct {
User string `json:"user" binding:"required"`
Password string `json:"password" binding:"required"`
}
func main() {
router := gin.Default()
router.POST("/login", func(c *gin.Context) {
var json Login
// 변환 과정 에러 처리 없음
if c.BindJSON(&json) == nil {
if json.User == "man" && json.Password == "123" {
c.JSON(200, gin.H{"status": "you are logged in"})
} else {
c.JSON(401, gin.H{"status": "unauthorized"})
}
}
})
router.Run()
}
이렇게 변수에 Json 데이터를 구조체로 맵핑하는 과정을 거쳐 Go에서 사용하게 된다.