Skip to content

Configuration

MeGaNeKo edited this page Mar 20, 2026 · 1 revision

Configuration

DefaultConfig

neoma.DefaultConfig(title, version) returns a ready-to-use configuration:

config := neoma.DefaultConfig("My API", "1.0.0")

What it sets:

Field Default Value
OpenAPIVersion "3.2.0" (core.OpenAPIVersion32)
OpenAPIPath "/openapi"
Docs.Path "/public/docs"
Docs.Provider openapi.ScalarProvider{}
Docs.Enabled true
SchemasPath "/schemas"
Formats JSON only (application/json)
DefaultFormat "application/json"
AllowAdditionalPropertiesByDefault true
FieldsOptionalByDefault true

Everything else is zero/nil and uses built-in defaults (e.g., ErrorHandler defaults to RFC9457Handler when nil).

Config Fields by Concern

OpenAPI

OpenAPIPath — URL path prefix for spec endpoints.

config.OpenAPIPath = "/openapi"
// Serves:
//   GET /openapi.json       (JSON)
//   GET /openapi.yaml       (YAML)
//   GET /openapi-3.0.json   (3.0 JSON, auto-downgraded)
//   GET /openapi-3.0.yaml   (3.0 YAML, auto-downgraded)

OpenAPIVersion — Which OpenAPI version to generate. Available constants:

core.OpenAPIVersion30 // "3.0.3"
core.OpenAPIVersion31 // "3.1.0"
core.OpenAPIVersion32 // "3.2.0" (default)

SchemasPath — Path for individual JSON Schema endpoints.

config.SchemasPath = "/schemas"
// Serves: GET /schemas/{schema-name}

Documentation

Docs — Controls the interactive API documentation UI.

config.Docs = core.DocsConfig{
	Path:        "/public/docs",
	Provider:    openapi.ScalarProvider{},
	Middlewares: core.Middlewares{authMiddleware},
	Enabled:     true,
}

Fields:

  • Path — URL where the docs UI is served.
  • Provider — Rendering engine. Built-in options: openapi.ScalarProvider{} (default), openapi.StoplightProvider{}, openapi.SwaggerUIProvider{}.
  • Middlewares — Middleware applied only to the docs endpoint (e.g., authentication).
  • Enabled — Set to false to disable serving docs entirely.

SwaggerUI with OAuth:

SwaggerUIProvider supports built-in OAuth configuration for APIs that use OAuth2 security schemes:

config.Docs = core.DocsConfig{
    Path: "/docs",
    Provider: openapi.SwaggerUIProvider{
        OAuthClientID: "my-client-id",
        OAuthScopes:   []string{"read", "write"},
    },
}

Content Negotiation

Formats — Map of content types to marshal/unmarshal implementations. DefaultConfig registers JSON. To add CBOR:

import "github.com/MeGaNeKoS/neoma/formats/cbor"

config.Formats["application/cbor"] = cbor.DefaultCBORFormat

DefaultFormat — Fallback content type when the client does not send an Accept header. Defaults to "application/json".

config.DefaultFormat = "application/json"

NoFormatFallback — When true, requests with an unrecognized Accept header are rejected instead of falling back to the default format. Defaults to false.

config.NoFormatFallback = true

Error Handling

ErrorHandler — Controls the error response format. When nil, defaults to RFC9457Handler. Implements the core.ErrorHandler interface.

Default (RFC 9457 with no custom URIs):

import "github.com/MeGaNeKoS/neoma/errors"

config.ErrorHandler = errors.NewRFC9457Handler()

RFC 9457 with custom type URIs and instance tracking:

config.ErrorHandler = errors.NewRFC9457HandlerWithConfig(
	"https://api.example.com/errors",
	func(ctx core.Context) string {
		return "/traces/" + getTraceID(ctx)
	},
)

No error schema in the OpenAPI spec:

config.ErrorHandler = errors.NewNoopHandler()

Convenience functions are also available for creating errors without a handler reference:

errors.ErrorNotFound("user not found")
errors.ErrorBadRequest("invalid input")
errors.ErrorN(http.StatusTeapot, "I'm a teapot")

Validation

RejectUnknownQueryParameters — When true, requests with unknown query parameters receive a 422 response. Can also be set per-operation. Defaults to false.

config.RejectUnknownQueryParameters = true

AllowAdditionalPropertiesByDefault — When true, generated object schemas allow additional properties beyond defined fields. Set to false to reject unknown JSON fields by default. Defaults to true.

config.AllowAdditionalPropertiesByDefault = false

FieldsOptionalByDefault — When true, struct fields are optional unless explicitly tagged as required. Set to false to make all exported fields required by default. Defaults to true.

config.FieldsOptionalByDefault = false

Internal Spec

InternalSpec — Enables a separate OpenAPI spec that includes hidden operations and fields, useful for internal tooling.

config.InternalSpec = core.InternalSpecConfig{
	Enabled:     true,
	Path:        "/internal/openapi",
	DocsPath:    "/internal/docs",
	Middlewares: core.Middlewares{adminOnly},
}

When enabled, this serves:

  • GET /internal/openapi.json and .yaml (all operations, including hidden)
  • GET /internal/openapi-3.0.json and .yaml (auto-downgraded, all operations)
  • GET /internal/docs (docs UI pointing to the internal spec)

Advanced

Transformers — Functions that modify response bodies before serialization. Receives the context, status string, and the value to transform.

config.Transformers = []core.Transformer{
	func(ctx core.Context, status string, v any) (any, error) {
		if m, ok := v.(map[string]any); ok {
			m["timestamp"] = time.Now().UTC()
		}
		return v, nil
	},
}

CreateHooks — Functions that modify the config before the API is fully initialized. Useful for plugins or conditional configuration.

config.CreateHooks = []func(core.Config) core.Config{
	func(c core.Config) core.Config {
		c.Info.Description = "Auto-configured"
		return c
	},
}

GenerateOperationID — Custom function for generating operation IDs. Receives the HTTP method and path. When nil, uses the built-in kebab-case generator (e.g., get-greet-by-name).

config.GenerateOperationID = func(method, path string) string {
	return strings.ToLower(method) + "_" + strings.ReplaceAll(path, "/", "_")
}

GenerateSummary — Custom function for generating operation summaries. Receives the HTTP method and path. When nil, uses the built-in generator (e.g., Get greet by name).

config.GenerateSummary = func(method, path string) string {
	return method + " " + path
}

SchemaNamer — Custom function for naming schemas in the registry. Receives the Go type and a hint string. When nil, uses the default namer which derives names from Go type names.

config.SchemaNamer = func(t reflect.Type, hint string) string {
	return t.PkgPath() + "." + t.Name()
}

ExcludeHiddenSchemas — When true, schemas used only by hidden operations are excluded from the public spec. Defaults to false.

config.ExcludeHiddenSchemas = true

SpecMiddlewares — Middleware applied to the OpenAPI spec endpoints (e.g., to require authentication for spec access).

config.SpecMiddlewares = core.Middlewares{
	func(ctx core.Context, next func(core.Context)) {
		if ctx.Header("X-API-Key") == "" {
			ctx.SetStatus(401)
			return
		}
		next(ctx)
	},
}

Full Config Struct Reference

type Config struct {
	*OpenAPI
	OpenAPIPath                        string
	OpenAPIVersion                     string
	Docs                               DocsConfig
	SchemasPath                        string
	SpecMiddlewares                    Middlewares
	Formats                            map[string]Format
	DefaultFormat                      string
	NoFormatFallback                   bool
	RejectUnknownQueryParameters       bool
	Transformers                       []Transformer
	CreateHooks                        []func(Config) Config
	ErrorHandler                       ErrorHandler
	GenerateOperationID                func(method, path string) string
	GenerateSummary                    func(method, path string) string
	SchemaNamer                        func(t reflect.Type, hint string) string
	InternalSpec                       InternalSpecConfig
	ExcludeHiddenSchemas               bool
	AllowAdditionalPropertiesByDefault bool
	FieldsOptionalByDefault            bool
}

All fields are defined in core/config.go.

Clone this wiki locally