API(Get List)

2024. 11. 24. 23:41·devops/go

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를 작성하면 될 것같다.

'devops > go' 카테고리의 다른 글

go fiber에 swagger를 붙여보자.  (0) 2024.11.27
Json Web Token  (0) 2024.11.26
Clean Architecture with go (Feat. fiber)  (1) 2024.11.25
clean-architecture 구성  (30) 2024.11.24
go fiber를 배워보자.  (30) 2024.11.22
'devops/go' 카테고리의 다른 글
  • Json Web Token
  • Clean Architecture with go (Feat. fiber)
  • clean-architecture 구성
  • go fiber를 배워보자.
꼬락이
꼬락이
ggorockee 님의 블로그 입니다.
  • 꼬락이
    꼬락이의 개발일지
    꼬락이
  • 전체
    오늘
    어제
    • 분류 전체보기 (30)
      • devops (28)
        • aws (0)
        • minikube (18)
        • go (10)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    k8s
    aws
    port-forwarding
    CICD
    GO
    repository
    CI
    golang
    Teleport
    cert-manager
    Minikube
    JWT
    Gorm
    argoc
    clean-archtiecture
    Github
    EC2
    db 우회
    ArgoCD
    istio
    helm
    Clean Architecture
    쿠버네티스
    systemd
    Github action
    SWAGGER
    Kubernetes
    DB 연결
    yq
    rds
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
꼬락이
API(Get List)
상단으로

티스토리툴바