单体服务
创建greet服务
$ cd ~/go-zero-single_demo
$ go mod init go-zero-single_demo
$ goctl api new greet
$ go mod tidy
目录结构
cd ~/go-zero-single_demo
tree
服务的目录结构:
.
├── go.mod
├── go.sum
├── etc
│ └── greet-api.yaml
├── greet.api
├── greet.go
└── internal
├── config
│ └── config.go
├── handler
│ ├── greethandler.go
│ └── routes.go
├── logic
│ └── greetlogic.go
├── svc
│ └── servicecontext.go
└── types
└── types.go
编写逻辑
vim go-zero-single_demo/greet/internal/logic/greetlogic.go
func (l *GreetLogic) Greet(req types.Request) (*types.Response, error) {
return &types.Response{
Message: "Hello go-zero""+req.Name,
}, nil
}
启动并访问服务
启动服务
$ cd ~/go-zero-single_demo/greet $ go run greet.go -f etc/greet-api.yaml
访问服务
$ curl -i -X GET \
http://localhost:8888/from/you
返回
HTTP/1.1 200 OK
Content-Type: application/json
Date: Sun, 07 Feb 2021 04:31:25 GMT
Content-Length: 27
{"message":"Hello go-zero name:you"}
goland启动配置:
greet.go -f etc/greet-api.yaml
修改GET入参
去除options限制的入参值
- 修改greet/greet.api 文件
type Request {
Name string `path:"name,options=you|me"`
}
修改为
type Request {
Name string `path:"name"`
}
- 重新生成代码
$ cd ~/go-zero-single_demo/greet
$ goctl api go -api greet.api -dir . -style gozero
文件greet/internal/types/types.go 会被重新生成
- 重启服务
$ cd ~/go-zero-single_demo/greet
$ go run greet.go -f etc/greet-api.yaml
- 访问服务
$ curl -i -X GET \
http://localhost:8888/from/haima
返回
{
"message": "Hello go-zero name:haima"
}
添加post请求
- 修改
greet/greet.api
文件
type RequestJson {
Name string `json:"name"`
}
service greet-api {
......
@handler GreetPostHandler
post /from/:name(RequestJson) returns (Response)
}
- 重新生成代码
$ cd ~/go-zero-single_demo/greet
$ goctl api go -api greet.api -dir . -style gozero
会成生以下两个文件
- greet/internal/handler/greetposthandler.go
- greet/internal/logic/greetpostlogic.go
文件greet/internal/types/types.go里会自动添加如下代码
type RequestJson struct {
Name string `json:"name"`
}
- 修改
greet/internal/logic/greetpostlogic.go
文件
func (l *GreetPostLogic) GreetPost(req types.RequestJson) (resp *types.Response, err error) {
// todo: add your logic here and delete this line
return &types.Response{
Message: "Hello go-zero name:"+req.Name,
}, nil
}
- 重启服务
$ cd ~/go-zero-single_demo/greet
$ go run greet.go -f etc/greet-api.yaml
post请求
新建
test.http
请求文件
###
GET http://127.0.0.1:8888/from/haima HTTP/1.1
###
POST http://127.0.0.1:8888/from/haima HTTP/1.1
Content-Type: application/json
{
"name":"post haima"
}
返回
{
"message": "Hello go-zero name:post haima"
}
作者:admin 创建时间:2022-12-31 07:57
最后编辑:海马 更新时间:2024-12-22 19:32
最后编辑:海马 更新时间:2024-12-22 19:32