converter

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2026 License: MIT Imports: 11 Imported by: 0

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

Examples

Constants

This section is empty.

Variables

Functions

func Generate

func Generate(opts ...Option) ([]*pluginpb.CodeGeneratorResponse_File, error)

Generate OpenAPI files with the given options.

func GenerateSingle

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

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

func WithAllowGET(allowGet bool) Option

WithAllowGET sets a file to use as a base for all OpenAPI files.

func WithBaseOpenAPI

func WithBaseOpenAPI(baseOpenAPI []byte) Option

WithBaseOpenAPI sets a file to use as a base for all OpenAPI files.

func WithContentTypes

func WithContentTypes(contentTypes ...string) Option

WithContentTypes sets a file to use as a base for all OpenAPI files.

func WithDebug

func WithDebug(enabled bool) Option

WithDebug sets up the logger to emit debug entries

func WithFeatures

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

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

func WithFormat(format string) Option

WithFormat sets the format for the OpenAPI file.

func WithFullyQualifiedMessageNames

func WithFullyQualifiedMessageNames(enabled bool) Option

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

func WithGoogleErrorDetail(enabled bool) Option

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

func WithIgnoreGoogleapiHTTP

func WithIgnoreGoogleapiHTTP(ignoreGoogleapiHTTP bool) Option

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

func WithIncludeNumberEnumValues

func WithIncludeNumberEnumValues(includeNumberEnumValues bool) Option

WithIncludeNumberEnumValues sets a file to use as a base for all OpenAPI files.

func WithLogger

func WithLogger(logger *slog.Logger) Option

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

func WithOnlyGoogleapiHTTP

func WithOnlyGoogleapiHTTP(onlyGoogleapiHTTP bool) Option

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

func WithPathPrefix

func WithPathPrefix(prefix string) Option

WithPathPrefix prepends a given string to each HTTP path.

func WithProtoAnnotations

func WithProtoAnnotations(enabled bool) Option

WithProtoAnnotations adds some details about protobuf to descrioptions.

func WithServiceDescriptions

func WithServiceDescriptions(enabled bool) Option

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

func WithServicePatterns

func WithServicePatterns(serviceNames []string) Option

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

func WithShortOperationIds(enabled bool) Option

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

func WithShortServiceTags

func WithShortServiceTags(enabled bool) Option

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

func WithStreaming(streaming bool) Option

WithStreaming sets a file to use as a base for all OpenAPI files.

Jump to

Keyboard shortcuts

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