기본 HTTP 서비스
이 가이드는 go-zero의 API framework를 사용해 최소 HTTP 서비스를 만드는 과정을 단계별로 설명합니다.
API 정의
섹션 제목: “API 정의”hello.api 파일을 만듭니다.
syntax = "v1"
type HelloReq { Name string `path:"name,options=you|me"`}
type HelloReply { Message string `json:"message"`}
service hello-api { @handler HelloHandler get /hello/:name (HelloReq) returns (HelloReply)}코드 생성
섹션 제목: “코드 생성”goctl api go -api hello.api -dir ./hello생성된 구조는 다음과 같습니다.
hello/├── etc/hello-api.yaml├── internal/│ ├── config/config.go│ ├── handler/hellohandler.go│ ├── logic/hellologic.go│ ├── svc/servicecontext.go│ └── types/types.go└── hello.go로직 구현
섹션 제목: “로직 구현”func (l *HelloLogic) Hello(req *types.HelloReq) (resp *types.HelloReply, err error) { return &types.HelloReply{ Message: "Hello " + req.Name, }, nil}Name: hello-apiHost: 0.0.0.0Port: 8888서버 시작
섹션 제목: “서버 시작”cd hello && go mod tidy && go run hello.go테스트
섹션 제목: “테스트”curl http://localhost:8888/hello/world# {"message":"Hello world"}오류 처리
섹션 제목: “오류 처리”import "github.com/zeromicro/go-zero/rest/httpx"
httpx.Error(w, errorx.NewCodeError(400, "invalid name"))