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{}, nil
withreturn &String{S: strings.ToUpper(req.S)}, nil
for example and rerun app. Check url:http://localhost:8080/strings/upper/test
and 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, defaultfalse
impl
-bool
, generate server implementation stub, defaulttrue
codec
-bool
, generate codec for parsing http request, and write http response, defaulttrue
swagger
-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