go get -u github.com/doroginin/protobuf/protoc-gen-go-http-server- Write your proto file
strings/strings.proto:
service Strings {
message String {
string s = 1;
}
rpc ToUpper (String) returns (String) {
option (google.api.http) = {
get: "/strings/upper/{string}"
};
}
}- Run code generation
protoc -I. -I/usr/local/include -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --gofast_out=plugins=grpc:. --go-http-server_out=. strings.proto- Write main file and run
package main
import (
"net/http"
"strings"
)
func main() {
http.ListenAndServe(":8080", strings.NewStringsHTTPServer())
}- Implement business logic in
strings.pb.server.impl.go. Replacereturn &String{}, nilwithreturn &String{S: strings.ToUpper(req.S)}, nilfor example and rerun app. Check url:http://localhost:8080/strings/upper/testand you will get result:
{
"s": "TEST"
}Profit 5. Add swagger if you want:
func main () {
swg := http.NewServeMux()
swg.Handle("/docs/swagger.json", strings.SwaggerJSONHandler)
swg.Handle("/docs/", http.StripPrefix("/docs", strings.SwaggerUIHandler))
http.ListenAndServe(":8080", strings.NewStringsHTTPServer(strings.WithFallbackHandler(swg)))
}and check http://localhost:8080/docs
Available protoc-gen-go-http-server options:
verbose-bool, show debug info, defaultfalseimpl-bool, generate server implementation stub, defaulttruecodec-bool, generate codec for parsing http request, and write http response, defaulttrueswagger-bool, generate swagger documentation handler, defaulttrue
using: protoc --go-http-server_out=verbose=true,impl=false,swagger=false,codec=false:. my.proto
- swagger gen
- middleware
- grpc server gen