Basic HTTP Service
Basic HTTP Service
Section titled “Basic HTTP Service”This guide walks you through creating a minimal HTTP service using go-zero’s API framework.
Define the API
Section titled “Define the API”Create 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)}Generate Code
Section titled “Generate Code”goctl api go -api hello.api -dir ./helloGenerated layout:
hello/├── etc/hello-api.yaml├── internal/│ ├── config/config.go│ ├── handler/hellohandler.go│ ├── logic/hellologic.go│ ├── svc/servicecontext.go│ └── types/types.go└── hello.goImplement Logic
Section titled “Implement Logic”func (l *HelloLogic) Hello(req *types.HelloReq) (resp *types.HelloReply, err error) { return &types.HelloReply{ Message: "Hello " + req.Name, }, nil}Configuration
Section titled “Configuration”Name: hello-apiHost: 0.0.0.0Port: 8888Start the Server
Section titled “Start the Server”cd hello && go mod tidy && go run hello.gocurl http://localhost:8888/hello/world# {"message":"Hello world"}Error Handling
Section titled “Error Handling”import "github.com/zeromicro/go-zero/rest/httpx"
httpx.Error(w, errorx.NewCodeError(400, "invalid name"))