更不便的在微信公众号阅读文章能够关注公众号:海生的go花园
在上一节文章里 go微服务框架Kratos(连载一):入门教程(装置以及跑通示例)咱们学会了 装置kratos。
本章节,咱们学习如何创立一个 http服务,以及对外提供 restful接口
一、运行样例
咱们先启动一个kratos样例的http服务
在上节创立的helloworld我的项目目录执行
go run ./cmd/helloworld -conf configs/config.yaml
能够启动http服务。
咱们关上 浏览器输出
http://localhost:8000/helloworld/1
会返回
能够发现样例运行胜利了。
二、样例api接口浏览
咱们关上应用kratos建设的样例我的项目helloworld,
在 greeter.proto文件里有 上面一个路由
get: "/helloworld/{name}"
2.1 批改样例,新增一个 get 申请
2.1.1 咱们关上 greeter.proto文件,对照 SayHello减少一个接口SayHi如下:
// Sends a hi rpc SayHi (HelloRequest) returns (HelloReply) { option (google.api.http) = { get: "/hi/{name}" }; }
写好后如下:
2.1.2 执行make api,生产api接口
➜ make api
输入:
protoc --proto_path=./api \ --proto_path=./third_party \ --go_out=paths=source_relative:./api \ --go-http_out=paths=source_relative:./api \ --go-grpc_out=paths=source_relative:./api \ --openapi_out=fq_schema_naming=true,default_response=false:. \ api/helloworld/v1/error_reason.proto api/helloworld/v1/greeter.proto
如果执行make api 报错,比方提醒,未装置 protoc-gen-go: program not found or is not executable,能够在 make api 执行之前,先执行一下 make init 装置一下kratos须要的依赖和插件。
此时咱们能够看 greeter_http.pb.go 外面的代码,减少SayHi()如下:
2.1.3 实现api接口SayHi()
咱们查看 SayHello()接口的实现,发现在 internal/service/greeter.go
那咱们实现SayHi()也同样在这样文件中。
咱们在 SayHello()办法下,写入如下代码:
// SayHi implements helloworld.GreeterServer.func (s *GreeterService) SayHi(ctx context.Context, in *v1.HelloRequest) (*v1.HelloReply, error) { g, err := s.uc.CreateGreeter(ctx, &biz.Greeter{Hello: in.Name}) if err != nil { return nil, err } return &v1.HelloReply{Message: "hi " + g.Hello}, nil}
此时显示如下:
2.1.4 在浏览器中拜访接口 http://localhost:8000/hi/1
咱们从新编译一下,
go run ./cmd/helloworld -conf configs/config.yaml
而后在浏览器中输出:http://localhost:8000/hi/1 展现如下:
咱们第一个get接口写胜利了。
2.2 批改样例,新增一个 post 申请
2.2.1 新增一个 Say() proto定义,如下:
// Say a hi rpc Say (HelloRequest) returns (HelloReply) { option (google.api.http) = { post: "/say", body: "*", }; }
咱们这里次要有两点批改
- post办法,以及api的url
- 定义承受的body为 "*"
2.2.2 执行make api,生成api接口
➜ make api
咱们会发现greeter_http.pb.go文件中GreeterHTTPServer中多了一个 Say()
type GreeterHTTPServer interface { Say(context.Context, *HelloRequest) (*HelloReply, error) SayHello(context.Context, *HelloRequest) (*HelloReply, error) SayHi(context.Context, *HelloRequest) (*HelloReply, error)}
2.2.3 在service中实现api接口Say()
在internal/service/greeter.go中实现 Say()办法,代码如下:
// Say implements helloworld.GreeterServer.func (s *GreeterService) Say(ctx context.Context, in *v1.HelloRequest) (*v1.HelloReply, error) { g, err := s.uc.CreateGreeter(ctx, &biz.Greeter{Hello: in.Name}) if err != nil { return nil, err } return &v1.HelloReply{Message: "say " + g.Hello}, nil}
2.2.4 申请post接口
此时咱们重启一下一下服务
go run ./cmd/helloworld -conf configs/config.yaml
而后模仿申请一下,胜利了。