
使用DeepSeek和Claude繪制出高質量的SVG 圖片
可以啟動http服務。
我們打開 瀏覽器輸入
http://localhost:8000/helloworld/1
會返回
可以發現樣例運行成功了。
我們打開使用kratos建立的樣例項目helloworld,
在 greeter.proto文件里有 下面一個路由
get: “/helloworld/{name}”
// Sends a hi
rpc SayHi (HelloRequest) returns (HelloReply) {
option (google.api.http) = {
get: "/hi/{name}"
};
}
寫好后如下:
? 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()如下:
我們查看 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
}
此時顯示如下:
我們重新編譯一下,
go run ./cmd/helloworld -conf configs/config.yaml
然后在瀏覽器中輸入:http://localhost:8000/hi/1 展示如下:
我們第一個get接口寫成功了。
// Say a hi
rpc Say (HelloRequest) returns (HelloReply) {
option (google.api.http) = {
post: "/say",
body: "*",
};
}
我們這里主要有兩點修改
? 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)
}
在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
}
此時我們重啟一下一下服務
go run ./cmd/helloworld -conf configs/config.yaml
然后模擬請求一下,成功了。