httpopenapi

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2025 License: MIT Imports: 10 Imported by: 0

README

httpopenapi

Go Reference

A lightweight adapter for the HTTP web framework that automatically generates OpenAPI 3.x specifications from your routes using oaswrap/spec.

Why httpopenapi?

  • ⚡ Seamless Integration — Works with your existing HTTP routes and handlers
  • 📝 Automatic Documentation — Generate OpenAPI specs from route definitions and struct tags
  • 🎯 Type Safety — Full Go type safety for OpenAPI configuration
  • 🔧 Built-in UI — Swagger UI served automatically at /docs
  • 🚀 Zero Overhead — Minimal performance impact on your API

Installation

go get github.com/oaswrap/spec/adapters/chiopenapi

Quick Start

package main

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

	"github.com/oaswrap/spec/adapters/httpopenapi"
	"github.com/oaswrap/spec/option"
)

func main() {
	mainMux := http.NewServeMux()
	r := httpopenapi.NewGenerator(mainMux,
		option.WithTitle("My API"),
		option.WithVersion("1.0.0"),
		option.WithSecurity("bearerAuth", option.SecurityHTTPBearer("Bearer")),
	)

	r.Route("/api/v1", func(r httpopenapi.Router) {
		r.HandleFunc("POST /login", LoginHandler).With(
			option.Summary("User login"),
			option.Request(new(LoginRequest)),
			option.Response(200, new(LoginResponse)),
		)
		auth := r.Group("/", AuthMiddleware).With(
			option.GroupSecurity("bearerAuth"),
		)
		auth.HandleFunc("GET /users/{id}", GetUserHandler).With(
			option.Summary("Get user by ID"),
			option.Request(new(GetUserRequest)),
			option.Response(200, new(User)),
		)
	})

	// Generate OpenAPI spec
	if err := r.WriteSchemaTo("openapi.yaml"); err != nil {
		log.Fatal(err)
	}

	log.Printf("🚀 OpenAPI docs available at: %s", "http://localhost:3000/docs")

	// Start the server
	if err := http.ListenAndServe(":3000", mainMux); err != nil {
		log.Fatal(err)
	}
}

type LoginRequest struct {
	Username string `json:"username" required:"true"`
	Password string `json:"password" required:"true"`
}

type LoginResponse struct {
	Token string `json:"token"`
}

type GetUserRequest struct {
	ID string `path:"id" required:"true"`
}

type User struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

func AuthMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Simulate authentication logic
		authHeader := r.Header.Get("Authorization")
		if authHeader != "" && authHeader == "Bearer example-token" {
			next.ServeHTTP(w, r)
		} else {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
		}
	})
}

func LoginHandler(w http.ResponseWriter, r *http.Request) {
	var req LoginRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "Invalid request", http.StatusBadRequest)
		return
	}
	// Simulate login logic
	_ = json.NewEncoder(w).Encode(LoginResponse{Token: "example-token"})
}

func GetUserHandler(w http.ResponseWriter, r *http.Request) {
	var req GetUserRequest
	id := r.PathValue("id")
	if id == "" {
		http.Error(w, "User ID is required", http.StatusBadRequest)
		return
	}
	req.ID = id
	// Simulate fetching user by ID
	user := User{ID: req.ID, Name: "John Doe"}
	_ = json.NewEncoder(w).Encode(user)
}

Configuration Options

For all available configuration options, see the main oaswrap/spec documentation.

API Reference

Contributing

We welcome contributions! Please open issues and PRs at the main oaswrap/spec repository.

License

MIT License — Created with ❤️ by Ahmad Faiz.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Generator

type Generator interface {
	Router

	// Validate checks if the OpenAPI schema is valid.
	Validate() error

	// GenerateSchema generates the OpenAPI schema in the specified formats.
	// Supported formats include "yaml", "json", etc.
	// If no formats are specified, it defaults to "yaml".
	GenerateSchema(formats ...string) ([]byte, error)

	// MarshalYAML generates the OpenAPI schema in YAML format.
	MarshalYAML() ([]byte, error)

	// MarshalJSON generates the OpenAPI schema in JSON format.
	MarshalJSON() ([]byte, error)

	// WriteSchemaTo writes the OpenAPI schema to a file in the specified format.
	WriteSchemaTo(filename string) error
}

Generator is an interface for generating OpenAPI documentation for HTTP applications.

func NewGenerator

func NewGenerator(mux *http.ServeMux, opts ...option.OpenAPIOption) Generator

func NewRouter

func NewRouter(mux *http.ServeMux, opts ...option.OpenAPIOption) Generator

type Route

type Route interface {
	// With applies operation options to the route.
	With(opts ...option.OperationOption) Route
}

Route is an interface for defining a route with OpenAPI options.

type Router

type Router interface {
	http.Handler

	// HandleFunc registers a handler function for the specified pattern.
	HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) Route

	// Handle registers a handler for the specified pattern.
	Handle(pattern string, handler http.Handler) Route

	// Group creates a new sub-router with the specified options.
	Group(prefix string, middlewares ...func(http.Handler) http.Handler) Router

	// Route creates a new route with the specified pattern and handler function.
	Route(prefix string, fn func(r Router), middlewares ...func(http.Handler) http.Handler) Router

	// With applies group level options to the router.
	With(opts ...option.GroupOption) Router
}

Router is an interface for handling HTTP routes with OpenAPI support.

Directories

Path Synopsis
example
basic command
internal

Jump to

Keyboard shortcuts

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