Documentation
¶
Overview ¶
protoc-gen-connect-openapi is a tool for generating OpenAPIv3.1 specs from protobuf. These specs are specific to the Connect protocol. See the github repo for more information: https://github.com/glebselyukov/protoc-gen-connect-openapi).
Index ¶
- Variables
- func Generate(opts ...Option) ([]*pluginpb.CodeGeneratorResponse_File, error)
- func GenerateSingle(opts ...Option) ([]byte, error)
- type Option
- func WithAllowGET(allowGet bool) Option
- func WithBaseOpenAPI(baseOpenAPI []byte) Option
- func WithContentTypes(contentTypes ...string) Option
- func WithDebug(enabled bool) Option
- func WithFeatures(features ...options.Feature) Option
- func WithFiles(files *protoregistry.Files) Option
- func WithFormat(format string) Option
- func WithFullyQualifiedMessageNames(enabled bool) Option
- func WithGlobal() Option
- func WithGoogleErrorDetail(enabled bool) Option
- func WithIgnoreGoogleapiHTTP(ignoreGoogleapiHTTP bool) Option
- func WithIncludeNumberEnumValues(includeNumberEnumValues bool) Option
- func WithLogger(logger *slog.Logger) Option
- func WithOnlyGoogleapiHTTP(onlyGoogleapiHTTP bool) Option
- func WithPathPrefix(prefix string) Option
- func WithProtoAnnotations(enabled bool) Option
- func WithServiceDescriptions(enabled bool) Option
- func WithServicePatterns(serviceNames []string) Option
- func WithServices(serviceNames []protoreflect.FullName) Option
- func WithShortOperationIds(enabled bool) Option
- func WithShortServiceTags(enabled bool) Option
- func WithSourceFiles(files *protoregistry.Files) Option
- func WithStreaming(streaming bool) Option
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var Convert = intconverter.Convert
Functions ¶
func Generate ¶
func Generate(opts ...Option) ([]*pluginpb.CodeGeneratorResponse_File, error)
Generate OpenAPI files with the given options.
func GenerateSingle ¶
Generate a single OpenAPI file.
Example ¶
package main
import (
"fmt"
"github.com/glebselyukov/protoc-gen-connect-openapi/converter"
)
func main() {
openapiBody, _ := converter.GenerateSingle(
converter.WithGlobal(),
converter.WithContentTypes(
"json",
"proto",
),
converter.WithStreaming(true),
converter.WithBaseOpenAPI([]byte(`
openapi: 3.1.0
info:
title: OpenAPI Documentation of gRPC Services
description: This is documentation that was generated from [protoc-gen-connect-openapi](https://github.com/glebselyukov/protoc-gen-connect-openapi).
`)))
fmt.Println(string(openapiBody))
}
Example (WithEndpoints) ¶
package main
import (
"bytes"
"encoding/base64"
"html/template"
"log"
"log/slog"
"net/http"
"time"
"buf.build/gen/go/connectrpc/eliza/connectrpc/go/connectrpc/eliza/v1/elizav1connect"
"github.com/glebselyukov/protoc-gen-connect-openapi/converter"
)
var tmplElements = template.Must(template.New("name").Parse(`<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>OpenAPI Documentation</title>
<script src="https://unpkg.com/@stoplight/[email protected]/web-components.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/@stoplight/[email protected]/styles.min.css">
</head>
<body>
<elements-api
id="docs"
router="hash"
layout="sidebar"
/>
<script>
(async () => {
const docs = document.getElementById('docs');
docs.apiDescriptionDocument = atob("{{ .DocumentBase64 }}");
})();
</script>
</body>
</html>`))
func main() {
mux := http.NewServeMux()
mux.Handle(elizav1connect.NewElizaServiceHandler(&elizav1connect.UnimplementedElizaServiceHandler{}))
openapiBody, err := converter.GenerateSingle(
converter.WithGlobal(),
converter.WithContentTypes(
"json",
"proto",
),
converter.WithStreaming(true),
converter.WithBaseOpenAPI([]byte(`
openapi: 3.1.0
info:
title: OpenAPI Documentation of gRPC Services
description: This is documentation that was generated from [protoc-gen-connect-openapi](https://github.com/glebselyukov/protoc-gen-connect-openapi).
`)))
if err != nil {
log.Fatalf("err: %s", err)
}
generationTime := time.Now()
mux.Handle("GET /openapi.html", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := tmplElements.Execute(w, struct{ DocumentBase64 string }{
DocumentBase64: base64.StdEncoding.EncodeToString(openapiBody),
}); err != nil {
slog.Error("rendering_template", "error", err)
}
}))
mux.Handle("GET /openapi.yaml", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.ServeContent(w, r, "openapi.yaml", generationTime, bytes.NewReader(openapiBody))
}))
addr := "127.0.0.1:6660"
log.Printf("Starting connectrpc on http://%s", addr)
log.Printf("OpenAPI Doc Page http://%s/openapi.html", addr)
log.Printf("OpenAPI Spec http://%s/openapi.yaml", addr)
srv := http.Server{
Addr: addr,
Handler: mux,
}
if err := srv.ListenAndServeTLS("cert.crt", "cert.key"); err != nil {
log.Fatalf("error: %s", err)
}
}
Types ¶
type Option ¶
type Option func(*generator) error
func WithAllowGET ¶
WithAllowGET sets a file to use as a base for all OpenAPI files.
func WithBaseOpenAPI ¶
WithBaseOpenAPI sets a file to use as a base for all OpenAPI files.
func WithContentTypes ¶
WithContentTypes sets a file to use as a base for all OpenAPI files.
func WithFeatures ¶
WithFeatures sets the features that are enabled.
func WithFiles ¶
func WithFiles(files *protoregistry.Files) Option
WithFiles will generate OpenAPI specs for the given files.
func WithFormat ¶
WithFormat sets the format for the OpenAPI file.
func WithFullyQualifiedMessageNames ¶
WithFullyQualifiedMessageNames decides if you want to use the full path in message names.
func WithGlobal ¶
func WithGlobal() Option
WithGlobal will generate OpenAPI specs for any service in the global registry. Shortcut for converter.WithFiles(protoregistry.GlobalFiles).
func WithGoogleErrorDetail ¶
WithGoogleErrorDetail enables the generation of error details using error_details.proto from google.rpc.
func WithIgnoreGoogleapiHTTP ¶
WithIgnoreGoogleapiHTTP tells the generator to ignore google.api.http options.
func WithIncludeNumberEnumValues ¶
WithIncludeNumberEnumValues sets a file to use as a base for all OpenAPI files.
func WithLogger ¶
WithLogger sets the logger to a given *slog.Logger instance. The default behavior will discard logs.
func WithOnlyGoogleapiHTTP ¶
WithOnlyGoogleapiHTTP tells the generator to only include methods with google.api.http options.
func WithPathPrefix ¶
WithPathPrefix prepends a given string to each HTTP path.
func WithProtoAnnotations ¶
WithProtoAnnotations adds some details about protobuf to descrioptions.
func WithServiceDescriptions ¶
WithServiceDescriptions decides if service names and their comments to be added to the end of info.description.
func WithServicePatterns ¶
WithServicePatterns will limit the services generated using glob patterns "company.service.*Service"
func WithServices ¶
func WithServices(serviceNames []protoreflect.FullName) Option
WithServices will limit the services generated.
func WithShortOperationIds ¶
WithShortOperationIds sets the operationId to shortServiceName + "_" + method short name instead of the full method name.
func WithShortServiceTags ¶
WithShortServiceTags uses the short service name instead of the full name for OpenAPI tags.
func WithSourceFiles ¶
func WithSourceFiles(files *protoregistry.Files) Option
WithSourceFiles adds the given files as source files but won't generate OpenAPI based on any services found in here.
func WithStreaming ¶
WithStreaming sets a file to use as a base for all OpenAPI files.