Skip to content

Basic HTTP Service

This guide walks you through creating a minimal HTTP service using go-zero’s API framework.

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)
}
Terminal window
goctl api go -api hello.api -dir ./hello

Generated layout:

hello/
├── etc/hello-api.yaml
├── internal/
│ ├── config/config.go
│ ├── handler/hellohandler.go
│ ├── logic/hellologic.go
│ ├── svc/servicecontext.go
│ └── types/types.go
└── hello.go
internal/logic/hellologic.go
func (l *HelloLogic) Hello(req *types.HelloReq) (resp *types.HelloReply, err error) {
return &types.HelloReply{
Message: "Hello " + req.Name,
}, nil
}
etc/hello-api.yaml
Name: hello-api
Host: 0.0.0.0
Port: 8888
Terminal window
cd hello && go mod tidy && go run hello.go
Terminal window
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"))