The framework provides open API/Swagger use in two ways: 1. Provide swagger interface on service, 2. Use the protoc plug-in to generate the swagger.json file. Here are two ways to do this.
Plugin swagger-api provides a range of swagger-related APIs, as well as the corresponding UI interface.
First install this plugin.
go get -u github.com/go-kratos/swagger-api
Then initialize and register in newHTTPServer of
internal/server/http.go, and try to put this route registration first to avoid match failed.
import "github.com/go-kratos/swagger-api/openapiv2" openAPIhandler := openapiv2.NewHandler()srv.HandlePrefix("/q/", openAPIhandler)
/q/swagger-ui/ in Web Browser in order to access Swagger UI
The new project Makefile has been integrated by default with the commands associated with generating swagger.json, and here's how to use them
First, install the protoc plug-in
go get -u github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2
Use the protoc command directly at the root of the project, note that modifying the final proto file path of the command is the actual path
protoc --proto_path=. \ --proto_path=./third_party \ --openapiv2_out . \ --openapiv2_opt logtostderr=true \ --openapiv2_opt json_names_for_fields=false \ api/helloworld/v1/greeter.proto
Once the above command has been executed successfully, the corresponding swagger.json file will be generated in the directory where your proto file is located. You can import it into any platform that supports the Open API specification for browsing, such as: