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/sudorandom/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 WithAllowedVisibilities(visibilities ...string) Option
- func WithBaseOpenAPI(baseOpenAPI []byte) Option
- func WithContentTypes(contentTypes ...string) Option
- func WithDebug(enabled bool) Option
- func WithDisableDefaultResponse(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 WithOverrideOpenAPI(overrideOpenAPI []byte) Option
- func WithPathPrefix(prefix string) Option
- func WithProtoAnnotations(enabled bool) Option
- func WithProtoNames(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
- func WithTrimUnusedTypes(enabled bool) Option
- func WithoutDefaultTags(enabled bool) Option
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var Convert = intconverter.Convert
Functions ¶
func Generate ¶ added in v0.10.0
func Generate(opts ...Option) ([]*pluginpb.CodeGeneratorResponse_File, error)
Generate OpenAPI files with the given options.
func GenerateSingle ¶ added in v0.10.0
Generate a single OpenAPI file.
Example ¶
package main
import (
"fmt"
"github.com/sudorandom/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/sudorandom/protoc-gen-connect-openapi).
`)))
fmt.Println(string(openapiBody))
}
Output:
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/sudorandom/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/elements@8.3.4/web-components.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/@stoplight/elements@8.3.4/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/sudorandom/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)
}
}
Output:
Types ¶
type Option ¶ added in v0.10.0
type Option func(*generator) error
func WithAllowGET ¶ added in v0.10.0
WithAllowGET allows methods with idempotency_level = NO_SIDE_EFFECTS to be documented with GET requests.
func WithAllowedVisibilities ¶ added in v0.25.6
WithAllowedVisibilities sets the visibility restriction labels to include.
func WithBaseOpenAPI ¶ added in v0.10.0
WithBaseOpenAPI sets a base OpenAPI document to merge into the generated output.
func WithContentTypes ¶ added in v0.10.0
WithContentTypes sets the content types to include in the generated OpenAPI output.
func WithDisableDefaultResponse ¶ added in v0.25.6
WithDisableDefaultResponse disables the default 200 response.
func WithFeatures ¶ added in v0.16.2
WithFeatures sets the features that are enabled.
func WithFiles ¶ added in v0.10.0
func WithFiles(files *protoregistry.Files) Option
WithFiles will generate OpenAPI specs for the given files.
func WithFormat ¶ added in v0.10.0
WithFormat sets the format for the OpenAPI file.
func WithFullyQualifiedMessageNames ¶ added in v0.15.15
WithFullyQualifiedMessageNames decides if you want to use the full path in message names.
func WithGlobal ¶ added in v0.10.0
func WithGlobal() Option
WithGlobal will generate OpenAPI specs for any service in the global registry. Shortcut for converter.WithFiles(protoregistry.GlobalFiles).
func WithGoogleErrorDetail ¶ added in v0.16.2
WithGoogleErrorDetail enables the generation of error details using error_details.proto from google.rpc.
func WithIgnoreGoogleapiHTTP ¶ added in v0.15.19
WithIgnoreGoogleapiHTTP tells the generator to ignore google.api.http options.
func WithIncludeNumberEnumValues ¶ added in v0.10.0
WithIncludeNumberEnumValues includes numeric values for enums in addition to string representations.
func WithLogger ¶ added in v0.16.2
WithLogger sets the logger to a given *slog.Logger instance. The default behavior will discard logs.
func WithOnlyGoogleapiHTTP ¶ added in v0.16.2
WithOnlyGoogleapiHTTP tells the generator to only include methods with google.api.http options.
func WithOverrideOpenAPI ¶ added in v0.25.6
WithOverrideOpenAPI sets an override OpenAPI document to merge on top of the generated output.
func WithPathPrefix ¶ added in v0.15.23
WithPathPrefix prepends a given string to each HTTP path.
func WithProtoAnnotations ¶ added in v0.14.0
WithProtoAnnotations adds some details about protobuf to descriptions.
func WithProtoNames ¶ added in v0.25.6
WithProtoNames uses protobuf field names instead of JSON names.
func WithServiceDescriptions ¶ added in v0.15.15
WithServiceDescriptions decides if service names and their comments to be added to the end of info.description.
func WithServicePatterns ¶ added in v0.16.2
WithServicePatterns will limit the services generated using glob patterns "company.service.*Service"
func WithServices ¶ added in v0.15.4
func WithServices(serviceNames []protoreflect.FullName) Option
WithServices will limit the services generated.
func WithShortOperationIds ¶ added in v0.16.2
WithShortOperationIds sets the operationId to shortServiceName + "_" + method short name instead of the full method name.
func WithShortServiceTags ¶ added in v0.16.2
WithShortServiceTags uses the short service name instead of the full name for OpenAPI tags.
func WithSourceFiles ¶ added in v0.10.0
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 ¶ added in v0.10.0
WithStreaming includes content types related to streaming.
func WithTrimUnusedTypes ¶ added in v0.25.6
WithTrimUnusedTypes removes types that aren't referenced by a service.
func WithoutDefaultTags ¶ added in v0.25.6
WithoutDefaultTags prevents adding default tags to converted fields.