devops/go

API(Get List)

꼬락이 2024. 11. 24. 23:41

1. Route 생성

api/routes/spot.go

package routes

import (
	"camping-backend-with-go/api/handlers"
	"camping-backend-with-go/pkg/spot"
	"github.com/gofiber/fiber/v2"
)

func SpotRouter(app fiber.Router, service spot.Service) {
	app.Get("/spots", handlers.GetSpots(service))
	app.Post("/spots", handlers.AddSpot(service))
}

 

2.  handler 생성

api/presenter/spot.go

...

func GetSpots(service spot.Service) fiber.Handler {
	return func(c *fiber.Ctx) error {
		fetched, err := service.FetchSpots()
		if err != nil {
			c.Status(http.StatusInternalServerError)
			return c.JSON(presenter.SpotErrorResponse(err))
		}
		return c.JSON(presenter.SpotsSuccessResponse(fetched))
	}
}

3.  service 생성

...

type Service interface {
	InsertSpot(spot *entities.Spot) (*entities.Spot, error)
	FetchSpots() (*[]presenter.Spot, error)
}

...
// FetchSpots is a service layer that helps fetch all Spots in SpotShop
func (s *service) FetchSpots() (*[]presenter.Spot, error) {
	return s.repository.ReadSpot()
}

4.  repository 생성

...
func (r *repository) ReadSpot() (*[]presenter.Spot, error) {
	var spots []presenter.Spot
	result := r.DBConn.Find(spots)
	if result.Error != nil {
		return nil, result.Error
	}

	return &spots, nil
}

5.  Postman으로  확인

panic: reflect: reflect.Value.Set using unaddressable value

 

이 에러메시지는 gorm에서 unmarshal error가 발생할 때 주로 나온다고 한다.

 

pkg/spot/repository.go

// result := r.DBConn.Find(spots)
result := r.DBConn.Find(&spots)

에서 이부분을 바꾸면 해결된다.

 

 

 

이제 정상적으로 요청되는 것을 확인할 수가 있다. 구조를 처음에 잡기는 어렵지만 한번 잡아놓으면 개발하기가 매우 수월하다. 이 페이스로 쭈욱 CRUD를 작성하면 될 것같다.