Hello World
Hello World
Section titled “Hello World”This page walks you through creating, running, and testing your first go-zero HTTP service from scratch. The whole thing takes about 5 minutes.
Prerequisites
Section titled “Prerequisites”- Go 1.21+ installed (
go version) - goctl installed (
goctl --version)
Not installed? See Install Go and Install goctl.
Step 1 — Scaffold the Project
Section titled “Step 1 — Scaffold the Project”goctl api new greetcd greetgo mod tidyThis creates a complete project layout:
greet/├── etc/│ └── greet-api.yaml # config: port, logging, etc.├── internal/│ ├── config/│ │ └── config.go # config struct│ ├── handler/│ │ ├── greethandler.go # HTTP handler (auto-generated)│ │ └── routes.go # route registration│ ├── logic/│ │ └── greetlogic.go # ← edit this: your business logic│ └── svc/│ └── servicecontext.go # shared dependencies (DB, cache, etc.)└── greet.go # main entrypointStep 2 — Look at the Generated DSL
Section titled “Step 2 — Look at the Generated DSL”Open greet.api:
type Request { Name string `path:"name,options=you|me"`}
type Response { Message string `json:"message"`}
service greet-api { @handler Greet get /from/:name (Request) returns (Response)}This single file is the source of truth. goctl generated all the Go code from it.
Step 3 — Run the Service
Section titled “Step 3 — Run the Service”go run greet.goExpected output:
Starting server at 0.0.0.0:8888...Step 4 — Test It
Section titled “Step 4 — Test It”Open a new terminal:
curl http://localhost:8888/from/youExpected response:
{"message":"Hello you"}Step 5 — Add Custom Logic
Section titled “Step 5 — Add Custom Logic”Open internal/logic/greetlogic.go. You’ll see:
func (l *GreetLogic) Greet(req *types.Request) (resp *types.Response, err error) { // todo: add your logic here and delete this line return}Replace it with:
func (l *GreetLogic) Greet(req *types.Request) (resp *types.Response, err error) { return &types.Response{ Message: fmt.Sprintf("Hello %s, welcome to go-zero!", req.Name), }, nil}Add the fmt import at the top of the file if needed. Save and re-run:
go run greet.gocurl http://localhost:8888/from/alice# {"message":"Hello alice, welcome to go-zero!"}How the Request Flows
Section titled “How the Request Flows”curl /from/alice → routes.go (route matching) → greethandler.go (parse + validate request) → greetlogic.go (your business logic) → greethandler.go (serialize response) → {"message":"..."}You only write the logic. go-zero handles routing, parsing, validation, serialization, and error wrapping.