OpenAPI specs for your Go server, generated at server runtime. No CLI, no code generation, and no HTTP

Overview

"oas" is short for "OpenAPI Spec". Go package for generating OpenAPI docs at runtime.

Non-features:

  • No code generation.
  • No CLI.
  • No magic comments.
  • No slowness.
  • No dependencies.
  • Nothing added to your HTTP stack.

Features:

  • Struct definitions for OpenAPI 3.1.
  • Uses reflection to make OAS schemas from your types.
    • No more maintaining separate definitions by hand.
    • The source of truth is your Go types. Not some external YAML.
    • Examines actual encoding behavior of your types, at runtime, to determine formats and nullability.
    • Supports references and cyclic types.
  • Uses Go structs to describe what can't be reflected (routes, descriptions, etc).
    • Structured, statically-typed format.
    • Not an ad-hoc data format in breakage-prone comments.
    • Not some external YAML.
  • The docs are Go structures. You can do anything with them:
    • Inspect and modify in Go.
    • Encode as JSON or YAML.
    • Write to disk at build time.
    • Serve to clients at runtime.
    • Visualize using an external tool.
  • Tiny and dependency-free.

See limitations below.

API docs: https://pkg.go.dev/github.com/mitranim/oas

Why

  • No external CLI.
    • Automatically downloaded like other libraries.
    • Automatically versioned via go.mod.
    • No manual CLI installation.
    • No manual CLI versioning.
  • No Go code generation.
    • No make generate when pulling or switching branches.
    • No waiting 1 minute for that stupidly slow generator.
    • No manual remapping from crappy generated types to the types you actually want to use.
    • No crappy 3rd party "middleware" in your HTTP stack.
  • No forced generation of OAS files. It's entirely optional.
    • No manual reruns of a generate command.
    • No bloating your commits and Git diffs with generated JSON/YAML.
    • Can generate and serve OAS purely at runtime.
  • No figuring out how to deal with built artifacts.
    • If you want built artifacts, it's an option. Your Go app is a CLI tool. Add a command to write its OAS to disk as JSON, and run that at build time.

Usage

This example focuses on the OAS docs, registering docs for routes, with schemas from Go types. Routing and server setup is elided.

import (
  "encoding/json"
  "net/http"

  o "github.com/mitranim/oas"
)

var doc = o.Doc{
  Openapi: o.Ver,
  Info:    &o.Info{Title: `API documentation for my server`},
}

type PageInput struct {
  Limit  uint64 `json:"limit"`
  Offset uint64 `json:"offset"`
}

type PersonPage struct {
  PageHead
  Vals []Person `json:"vals"`
}

type PageHead struct {
  Keys []string `json:"keys"`
  More bool     `json:"more"`
}

type Person struct {
  Id   string `json:"id"`
  Name string `json:"name"`
}

var _ = doc.Route(`/api/persons`, http.MethodGet, o.Op{
  ReqBody: doc.JsonBodyOpt(PageInput{}),
  Resps:   doc.RespsOkJson(PersonPage{}),
  Desc:    `Serves a single page from a person feed, paginated.`,
})

func servePersonFeed(rew http.ResponseWriter, req *http.Request) {
  // Mock implementation for example's sake.
  try(json.NewEncoder(rew).Encode(PersonPage{}))
}

var _ = doc.Route(`/openapi.json`, http.MethodGet, o.Op{
  Resps: doc.RespsOkJson(nil),
  Desc: `
Serves the OpenAPI documentation for this server in JSON format.
The docs' docs are elided from the docs to avoid bloat.
`,
})

func serveDocs(rew http.ResponseWriter, _ *http.Request) {
  try(json.NewEncoder(rew).Encode(&doc))
}

func try(err error) {
  if err != nil {
    panic(err)
  }
}

Limitations

The following features are currently missing, but may be added on demand:

  • Describing generic/parametrized types.
    • Current plan: wait for Go generics, which are expected in 1.18 on Feb 2022.
  • Router integration.
    • Integration with github.com/mitranim/rout is planned.

This package doesn't provide a UI. You're expected to feed the resulting JSON into one of many externally-available tools for Swagger UI / OpenAPI UI. Many tools can consume specs from a URL, such as your server's endpoint for serving the spec.

License

https://unlicense.org

Misc

I'm receptive to suggestions. If this library almost satisfies you but needs changes, open an issue or chat me up. Contacts: https://mitranim.com/#contacts

Owner
Nelo Mitranim
Lead software developer. Open source enthusiast.
Nelo Mitranim
Similar Resources

HTTP server receives events and publishes them to STAN

HTTP server receives events and publishes them to STAN

Publishes events to Nats Streaming(STAN) synchornously and asynchronously. Cache events's publish-state using Redis and Store events using MongoDB.

Dec 30, 2022

Minimal HTTP File Server for pentesting written in Go

Minimal HTTP File Server for pentesting written in Go

Golang implementation of simple HTTP server with upload feature.

Aug 4, 2022

HTTP Echo is a go web server that echos back the arguments given to it.

HTTP Echo is a go web server that echos back the arguments given to it. This is especially useful for demos or a more extensive "hello world" application in Docker or Kubernetes.

Jan 3, 2023

A simple Go HTTP server that proxies RPC provider requests

go-rpc-provider-proxy A simple Go HTTP server that proxies RPC provider requests.

Nov 21, 2021

Simple HTTP server written in golang

Simple HTTP server written in golang Simple webserver in golang, to demonstrate basic functionalities like e.g. sending back some request header info,

Aug 31, 2022

Go-simplehttp - Simple HTTP server written in golang

Simple HTTP server written in golang Simple webserver in golang, to demonstrate

Jan 1, 2022

A simple server with REST API to keep track of your TODOs (with html interface).

A simple server with REST API to keep track of your TODOs (with html interface).

TODOserver A simple server written in GO using gin and gorm. Getting started Download the repository docker build -t todoserver . docker run -p 8888:8

Nov 10, 2021

Go web server - A web server that can accept a GET request and serve a response.

go_web_server A web server that can accept a GET request and serve a response. Go is a great language for creating simple yet efficient web servers an

Jan 3, 2022

Tiny Go webserver that prints os information and HTTP request to output

whoami Tiny Go webserver that prints os information and HTTP request to output Usage Paths /data?size=n[&unit=u]: creates a response with a size n. Th

Nov 2, 2021
a simple http server as replacement of python -m http.server

ser a simple http server as replacement of python -m http.server

Dec 5, 2022
Fishserver is designed to quickly add HTTP handlers to HTTP servers. It supports registration of various HTTP
Fishserver is designed to quickly add HTTP handlers to HTTP servers. It supports registration of various HTTP

Fishserver is designed to quickly add HTTP handlers to HTTP servers. It supports registration of various HTTP. Handler interface types such as Gin Engine, Go's built-in HTTP. HandlerFunc, or http.ServeMux. The HTTP server can be configured quickly with options and can be used for test cases.

Nov 1, 2021
✨ A lightweight HTTP server based on GO, will try to detect your OS and architecture and return as SHELL script. ✨
✨ A lightweight HTTP server based on GO, will try to detect your OS and architecture and return as SHELL script. ✨

✨ A lightweight HTTP server based on GO, will try to detect your OS and architecture and return as SHELL script. ✨

Dec 14, 2022
A simple HTTP Server to share files over WiFi via Qr Code
A simple HTTP Server to share files over WiFi via Qr Code

go-fileserver A simple HTTP server to share files over WiFi via QRCode Installation You can download compressed version from

Oct 8, 2022
A simple http-web server logging incoming requests to stdout with simple http-interface.
A simple http-web server logging incoming requests to stdout with simple http-interface.

http-cli-echo-logger A simple http-web server logging incoming requests to stdout with simple http-interface. Run locally go run ./cmd/main.go Default

Jul 18, 2022
GRPC And REST Server Code challenge

Code challenge This repo contains 2 entry points. 1. GRPC Server (cmd/grpcserver/main.go) The grpc server exposes two rpcs: rpc SaveVLAN (VLAN) return

Nov 16, 2021
:tophat: Small self-contained pure-Go web server with Lua, Markdown, HTTP/2, QUIC, Redis and PostgreSQL support
:tophat: Small self-contained pure-Go web server with Lua, Markdown, HTTP/2, QUIC, Redis and PostgreSQL support

Web server with built-in support for QUIC, HTTP/2, Lua, Markdown, Pongo2, HyperApp, Amber, Sass(SCSS), GCSS, JSX, BoltDB (built-in, stores the databas

Jan 1, 2023
A feature flag solution, with only a YAML file in the backend (S3, GitHub, HTTP, local file ...), no server to install, just add a file in a central system and refer to it. 🎛️
A feature flag solution, with only a YAML file in the backend (S3, GitHub, HTTP, local file ...), no server to install, just add a file in a central system and refer to it. 🎛️

??️ go-feature-flag A feature flag solution, with YAML file in the backend (S3, GitHub, HTTP, local file ...). No server to install, just add a file i

Dec 29, 2022
Opinionated boilerplate Golang HTTP server with CORS, OPA, Prometheus, rate-limiter for API and static website.
Opinionated boilerplate Golang HTTP server with CORS, OPA, Prometheus, rate-limiter for API and static website.

Teal.Finance/Server Opinionated boilerplate HTTP server with CORS, OPA, Prometheus, rate-limiter… for API and static website. Origin This library was

Nov 3, 2022