swagger로 post 요청을 날리려고 봤는데 Register User의 Input Schema에 id가 들어가 있는 것이다.
물론 여기에 id를 쓰지 않고 요청을 날려도 그대로 성공하지만 이 것은 매우 맘에 안드는 일이다.
하 정말로 버그가 끝이 없다...
그대로 어쩌겠는가 이거부터 손보고 다음 스텝으로 넘어가야겠다..
일단 문제는 Swagger에서 사용하는 Input Schema와 Gorm에서 사용하는 스키마가 동일하여 나타나는 현상인거 같아
Input Schema를 따로 만들어주기로 했다.
type CreateUserSchema struct {
Email string `json:"email"`
Password string `json:"password"`
Username string `json:"username"`
}
이렇게 선언해주고 나서 swagger를 작성하는 handler에 붙여서 확인해보기로 한다.
이제 정상적으로 보이는 것을 확인할 수가 있다.
흠... 이제 그렇다면 나머지 모든 API들을 이렇게 Shema를 만들어서 붙여야겠다.
Auth
Auth부터 시작하자.
Auth의 Handler를 보니
func Login(service auth.Service) fiber.Handler {
// Logic..
}
이렇게만 있는걸 보니 Login Schema만 만들어주면 될 것 같다. Login Schema는 Email과 Password만 필요하니 일단 이것만 만들어주도록하자.
type LoginSchema struct {
Email string `json:"email"`
Password string `json:"password"`
}
이렇게 만들어주고 위의 Handler에 연결하자.
// Login is a function to Login
// @Summary Login
// @Description Login
// @Tags Auth
// @Accept json
// @Produce json
// @Param user body entities.LoginSchema true "Login Schema"
// @Success 200 {object} presenter.JsonResponse{data=string}
// @Failure 503 {object} presenter.JsonResponse
// @Router /auth/login [post]
func Login(service auth.Service) fiber.Handler {
return func(c *fiber.Ctx) error {
// request parser
var requestBody entities.Login
if err := c.BodyParser(&requestBody); err != nil {
return c.Status(http.StatusBadRequest).JSON(presenter.AuthErrorResponse(err))
}
token, err := service.Login(&requestBody)
if err != nil {
return c.Status(http.StatusBadRequest).JSON(presenter.AuthErrorResponse(err))
}
return c.Status(http.StatusOK).JSON(presenter.AuthSuccessfulResponse(token))
}
}
$ swag init --parseDependency
$ go run main.go
이렇게 입력하고 http://localhost:3000/v1/docs로 접속하면 다음과 같은 화면을 볼 수 있다. Login Schema도 잘들어갔다.
실제로 로그인을해보자. 토큰을 뱉어내는지 두구두구~~~
token을 리턴했으니 로그인이 정상적으로 된거다. 한개만 더 확인해보자.
이 user의 user_id는 "1"이다. jwt token을 복호화했을 때 user_id가 1이 나오는지 확인해보면 되겠다.
user_id가 1인 것을 확인할 수 있다. 로그인 인증은 아주 잘된다. 이제 나머지것들을 하자.
HealthCheck
HealthCheck는 Get 요청만 있으므로 한개만 추가하면 된다.
그리고 이 때는 post요청이 아니라 get만 요청하므로 response만 잘 다루면 될 거 같다.
// GetHealthCheck is a function to healthcheck
// @Summary Health Check
// @Description Health Check
// @Tags HealthCheck
// @Accept json
// @Produce json
// @Success 200 {object} presenter.JsonResponse
// @Failure 503 {object} presenter.JsonResponse
// @Router /healthcheck [get]
func GetHealthCheck(service healthcheck.Service) fiber.Handler {
return func(c *fiber.Ctx) error {
err := service.GetHealthCheck()
if err != nil {
c.Status(http.StatusInternalServerError)
return c.JSON(presenter.HealthCheckErrorResponse(err))
}
return c.Status(http.StatusOK).JSON(presenter.HealthCheckSuccessResponse())
}
}
요청도 정상적으로 들어갔다.
Spot
Spot은 Handler가 좀 많다.
func AddSpot(service spot.Service) fiber.Handler {
...
}
func GetSpots(service spot.Service) fiber.Handler {
...
}
func UpdateSpot(service spot.Service) fiber.Handler {
...
}
func GetSpot(service spot.Service) fiber.Handler {
...
}
func PartialUpdateSpot(service spot.Service) fiber.Handler {
...
}
func RemoveSpot(service spot.Service) fiber.Handler {
...
}
총 6개에 대해서 해줘야한다. (좀 많긴하네 ...) 이작업을 처음부터 했으면 됐는데 앞으로는 swagger를 붙이면서 개발해야겠다.
일단 Schema부터 만들자.
type CreateSpotSchema struct {
Title string `json:"title"`
Location string `json:"location"`
Author string `json:"author"`
}
type UpdateSpotSchema struct {
Title string `json:"title"`
Location string `json:"location"`
}
이 스키를 이용해서 handler에 붙이도록 하겠다.
// AddSpot is a function to create spot data to database
// @Summary AddSpot
// @Description AddSpot
// @Tags Spot
// @Accept json
// @Produce json
// @Param user body entities.CreateSpotSchema true "Create Spot"
// @Success 200 {object} presenter.JsonResponse{data=presenter.Spot}
// @Failure 503 {object} presenter.JsonResponse
// @Router /spot [post]
func AddSpot(service spot.Service) fiber.Handler {
...
}
// GetSpots is a function to get all spot data from database
// @Summary GetSpots
// @Description GetSpots
// @Tags Spot
// @Accept json
// @Produce json
// @Success 200 {object} presenter.JsonResponse{data=[]presenter.Spot}
// @Failure 503 {object} presenter.JsonResponse
// @Router /spot [get]
func GetSpots(service spot.Service) fiber.Handler {
...
}
// UpdateSpot is a function to update spot data to database
// @Summary UpdateSpot
// @Description UpdateSpot
// @Tags Spot
// @Accept json
// @Produce json
// @Param id path int true "Spot id"
// @Param user body entities.UpdateSpotSchema true "Update Spot"
// @Success 200 {object} presenter.JsonResponse{data=presenter.Spot}
// @Failure 503 {object} presenter.JsonResponse
// @Router /spot/{id} [put]
func UpdateSpot(service spot.Service) fiber.Handler {
...
}
// GetSpot is a function to get spot data to database
// @Summary GetSpot
// @Description GetSpot
// @Tags Spot
// @Accept json
// @Produce json
// @Param id path int true "Spot id"
// @Success 200 {object} presenter.JsonResponse{data=presenter.Spot}
// @Failure 503 {object} presenter.JsonResponse
// @Router /spot/{id} [get]
func GetSpot(service spot.Service) fiber.Handler {
...
}
// PartialUpdateSpot is a function to update spot data to database
// @Summary PartialUpdateSpot
// @Description PartialUpdateSpot
// @Tags Spot
// @Accept json
// @Produce json
// @Param id path int true "Spot id"
// @Param user body entities.UpdateSpotSchema true "Update Spot"
// @Success 200 {object} presenter.JsonResponse{data=presenter.Spot}
// @Failure 503 {object} presenter.JsonResponse{}
// @Router /spot/{id} [patch]
func PartialUpdateSpot(service spot.Service) fiber.Handler {
...
}
// RemoveSpot is a function to delete spot data to database
// @Summary RemoveSpot
// @Description RemoveSpot
// @Tags Spot
// @Accept json
// @Produce json
// @Param id path int true "Spot id"
// @Success 200 {object} presenter.JsonResponse{}
// @Failure 503 {object} presenter.JsonResponse{}
// @Router /spot/{id} [delete]
func RemoveSpot(service spot.Service) fiber.Handler {
...
}
이렇게 모두 작성하고 나서
$ swag init --parseDependency
$ go run main.go
http://localhost:3000/v1/docs 에 들어가면 다음과 같은 화면을 볼 수가 있는데
테스트한 결과 모두 잘 동작하는 것을 볼 수가 있다.
이렇게 현재까지 작성한 API를 붙였다.
이제 해결해야할 문제는 다음과 같다.
Spot을 만들 때 Author를 직접입력하게 되어있다. 로그인이 되어있는 User만 이 API를 호출할 수가 있고 로그인이 되어있다면 이 JWT를 이용해서 username을 자동으로 등록하게 하겠다.
'devops > go' 카테고리의 다른 글
Change Password 및 JWT middle ware (0) | 2024.11.29 |
---|---|
DB 우회 (0) | 2024.11.29 |
go fiber에 swagger를 붙여보자. (0) | 2024.11.27 |
Json Web Token (0) | 2024.11.26 |
Clean Architecture with go (Feat. fiber) (1) | 2024.11.25 |