converter

package
v0.25.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 14, 2026 License: MIT Imports: 11 Imported by: 1

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

Examples

Constants

This section is empty.

Variables

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

func GenerateSingle(opts ...Option) ([]byte, error)

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))
}
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)
	}
}

Types

type Option added in v0.10.0

type Option func(*generator) error

func WithAllowGET added in v0.10.0

func WithAllowGET(allowGet bool) Option

WithAllowGET allows methods with idempotency_level = NO_SIDE_EFFECTS to be documented with GET requests.

func WithAllowedVisibilities added in v0.25.6

func WithAllowedVisibilities(visibilities ...string) Option

WithAllowedVisibilities sets the visibility restriction labels to include.

func WithBaseOpenAPI added in v0.10.0

func WithBaseOpenAPI(baseOpenAPI []byte) Option

WithBaseOpenAPI sets a base OpenAPI document to merge into the generated output.

func WithContentTypes added in v0.10.0

func WithContentTypes(contentTypes ...string) Option

WithContentTypes sets the content types to include in the generated OpenAPI output.

func WithDebug added in v0.13.0

func WithDebug(enabled bool) Option

WithDebug sets up the logger to emit debug entries

func WithDisableDefaultResponse added in v0.25.6

func WithDisableDefaultResponse(enabled bool) Option

WithDisableDefaultResponse disables the default 200 response.

func WithFeatures added in v0.16.2

func WithFeatures(features ...options.Feature) Option

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

func WithFormat(format string) Option

WithFormat sets the format for the OpenAPI file.

func WithFullyQualifiedMessageNames added in v0.15.15

func WithFullyQualifiedMessageNames(enabled bool) Option

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

func WithGoogleErrorDetail(enabled bool) Option

WithGoogleErrorDetail enables the generation of error details using error_details.proto from google.rpc.

func WithIgnoreGoogleapiHTTP added in v0.15.19

func WithIgnoreGoogleapiHTTP(ignoreGoogleapiHTTP bool) Option

WithIgnoreGoogleapiHTTP tells the generator to ignore google.api.http options.

func WithIncludeNumberEnumValues added in v0.10.0

func WithIncludeNumberEnumValues(includeNumberEnumValues bool) Option

WithIncludeNumberEnumValues includes numeric values for enums in addition to string representations.

func WithLogger added in v0.16.2

func WithLogger(logger *slog.Logger) Option

WithLogger sets the logger to a given *slog.Logger instance. The default behavior will discard logs.

func WithOnlyGoogleapiHTTP added in v0.16.2

func WithOnlyGoogleapiHTTP(onlyGoogleapiHTTP bool) Option

WithOnlyGoogleapiHTTP tells the generator to only include methods with google.api.http options.

func WithOverrideOpenAPI added in v0.25.6

func WithOverrideOpenAPI(overrideOpenAPI []byte) Option

WithOverrideOpenAPI sets an override OpenAPI document to merge on top of the generated output.

func WithPathPrefix added in v0.15.23

func WithPathPrefix(prefix string) Option

WithPathPrefix prepends a given string to each HTTP path.

func WithProtoAnnotations added in v0.14.0

func WithProtoAnnotations(enabled bool) Option

WithProtoAnnotations adds some details about protobuf to descriptions.

func WithProtoNames added in v0.25.6

func WithProtoNames(enabled bool) Option

WithProtoNames uses protobuf field names instead of JSON names.

func WithServiceDescriptions added in v0.15.15

func WithServiceDescriptions(enabled bool) Option

WithServiceDescriptions decides if service names and their comments to be added to the end of info.description.

func WithServicePatterns added in v0.16.2

func WithServicePatterns(serviceNames []string) Option

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

func WithShortOperationIds(enabled bool) Option

WithShortOperationIds sets the operationId to shortServiceName + "_" + method short name instead of the full method name.

func WithShortServiceTags added in v0.16.2

func WithShortServiceTags(enabled bool) Option

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

func WithStreaming(streaming bool) Option

WithStreaming includes content types related to streaming.

func WithTrimUnusedTypes added in v0.25.6

func WithTrimUnusedTypes(enabled bool) Option

WithTrimUnusedTypes removes types that aren't referenced by a service.

func WithoutDefaultTags added in v0.25.6

func WithoutDefaultTags(enabled bool) Option

WithoutDefaultTags prevents adding default tags to converted fields.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL