HTTP 基础开发
本指南将带你使用 go-zero 的 API 框架创建一个最简 HTTP 服务。
定义 API
Section titled “定义 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实现业务逻辑
Section titled “实现业务逻辑”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: 8888cd hello && go mod tidy && go run hello.gocurl http://localhost:8888/hello/world# {"message":"Hello world"}import "github.com/zeromicro/go-zero/rest/httpx"
httpx.Error(w, errorx.NewCodeError(400, "invalid name"))