gindocnic

package module
v0.0.11 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2025 License: MIT Imports: 7 Imported by: 0

README

Gindocnic

Go Report Card Go Reference release

A library for generating OpenAPI 3.1 documentation for the Gin Web Framework.

Usage

A basic example:

doc := NewDoc()
r := gin.Default()

request := struct {
    Id int `json:"id" binding:"required"`
}{}
spec := func(p *PathItemSpec) {
    p.AddRequest(request)
}
r.POST("/pets", doc.Operation(func(c *gin.Context) {}, spec))
if err := doc.AssocRoutesInfo(r.Routes()); err != nil {
    log.Fatalf("%#v", err)
}
yml, err := doc.MarshalYAML()
if err != nil {
    log.Fatalf("%#v", err)
}
fmt.Println(string(yml))

Output:

openapi: 3.1.0
info:
  title: ""
  version: ""
paths:
  /pets:
    post:
      operationId: pets0
      requestBody:
        content:
          application/json:
            schema:
              properties:
                id:
                  type: integer
              required:
              - id
              type: object
      responses:
        "204":
          description: No Content
      summary: ""

Further examples are available in the API documentation on go.dev.

Contributing

Documentation

Overview

Package gindocnic is a library for generating OpenAPI3.1 documentation for the Gin Web Framework.

Example

Example

package main

import (
	"fmt"
	"github.com/alpdr/gindocnic"
	"github.com/gin-gonic/gin"
	"io"
	"log"
	"net/http"
	"os"
)

type AddPetRequest struct {
	ID         int    `json:"id" binding:"required"`
	CustomerID string `header:"customerId" description:"identifies a customer"`
	TrackingID string `cookie:"trackingId"`
}

type Response struct {
	Id int `json:"id"`
}

type ErrorResponse struct {
	Error string `json:"error"`
}

func (h *Handler) addSpec(p *gindocnic.PathItemSpec) {
	p.SetSummary("Add a new pet to the store")
	p.AddRequest(AddPetRequest{})
	p.AddResponse(Response{}, gindocnic.ResponseStatus(http.StatusCreated))
	p.AddResponse(ErrorResponse{}, gindocnic.ResponseStatus(http.StatusBadRequest))
}
func (h *Handler) addPet(c *gin.Context) {}

type GetPetRequest struct {
	ID int `uri:"id"`
}

func (h *Handler) getSpec(p *gindocnic.PathItemSpec) {
	p.SetSummary("Find a pet")
	p.AddRequest(GetPetRequest{})
	p.AddResponse(Response{})
	p.AddResponse(ErrorResponse{}, gindocnic.ResponseStatus(http.StatusNotFound))
}
func (h *Handler) getPet(c *gin.Context) {}

type SearchPetsRequest struct {
	Name string `query:"name"`
}

func (h *Handler) searchSpec(p *gindocnic.PathItemSpec) {
	p.SetSummary("Search for pets")
	p.AddRequest(SearchPetsRequest{})
	p.AddResponse(Response{})
	p.AddResponse(ErrorResponse{}, gindocnic.ResponseStatus(http.StatusNotFound))
}
func (h *Handler) searchPets(c *gin.Context) {}

type Handler struct{}

// Example
func main() {
	doc := gindocnic.MakeDoc().
		WithServer(gindocnic.Server{URL: "https://github.com/alpdr/gindocnic"}).
		WithoutSecurities().
		WithSummary("example API").
		WithLicense(gindocnic.License{Name: "Proprietary", URL: "https://uzabase.com"})

	gin.DefaultWriter = io.Discard
	defer func() {
		gin.DefaultWriter = os.Stdout
	}()
	r := gin.Default()

	handler := Handler{}

	r.POST("/pets", doc.Operation(handler.addPet, handler.addSpec))
	r.GET("/pets/{id}", doc.Operation(handler.getPet, handler.getSpec))
	r.GET("/pets", doc.Operation(handler.searchPets, handler.searchSpec))
	if err := doc.AssocRoutesInfo(r.Routes()); err != nil {
		log.Fatalf("%#v", err)
	}

	yml, err := doc.MarshalYAML()
	if err != nil {
		log.Fatalf("%#v", err)
	}

	fmt.Println(string(yml))
}
Output:

openapi: 3.1.0
info:
  license:
    name: Proprietary
    url: https://uzabase.com
  summary: example API
  title: ""
  version: ""
servers:
- url: https://github.com/alpdr/gindocnic
paths:
  /pets:
    get:
      operationId: pets1
      parameters:
      - in: query
        name: name
        schema:
          type: string
      responses:
        "200":
          content:
            application/json:
              schema:
                properties:
                  id:
                    type: integer
                type: object
          description: OK
        "404":
          content:
            application/json:
              schema:
                properties:
                  error:
                    type: string
                type: object
          description: Not Found
      summary: Search for pets
    post:
      operationId: pets0
      parameters:
      - in: cookie
        name: trackingId
        schema:
          type: string
      - description: identifies a customer
        in: header
        name: customerId
        schema:
          description: identifies a customer
          type: string
      requestBody:
        content:
          application/json:
            schema:
              properties:
                id:
                  type: integer
              required:
              - id
              type: object
        required: true
      responses:
        "201":
          content:
            application/json:
              schema:
                properties:
                  id:
                    type: integer
                type: object
          description: Created
        "400":
          content:
            application/json:
              schema:
                properties:
                  error:
                    type: string
                type: object
          description: Bad Request
      summary: Add a new pet to the store
  /pets/{id}:
    get:
      operationId: petsid2
      parameters:
      - in: path
        name: id
        required: true
        schema:
          type: integer
      responses:
        "200":
          content:
            application/json:
              schema:
                properties:
                  id:
                    type: integer
                type: object
          description: OK
        "404":
          content:
            application/json:
              schema:
                properties:
                  error:
                    type: string
                type: object
          description: Not Found
      summary: Find a pet
security:
- {}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func RequestContentType

func RequestContentType(contentType string) func(ro *requestOptions)

RequestContentType defines the content type of the request.

func ResponseDescription added in v0.0.10

func ResponseDescription(description string) responseOption

func ResponseStatus

func ResponseStatus(status int) responseOption

Types

type Doc

type Doc struct {
	// contains filtered or unexported fields
}

Doc represents the root of an OpenAPIv3.1 document.

func MakeDoc added in v0.0.8

func MakeDoc() Doc

MakeDoc returns Doc.

func (Doc) AssocRoutesInfo

func (d Doc) AssocRoutesInfo(routes gin.RoutesInfo) error

AssocRoutesInfo associates HTTP paths and methods with their corresponding handlers to generate path item objects.

func (Doc) MarshalYAML

func (d Doc) MarshalYAML() ([]byte, error)

MarshalYAML returns the YAML encoding of Doc.

func (Doc) Operation

func (d Doc) Operation(h gin.HandlerFunc, opts ...PathItemSpecFunc) gin.HandlerFunc

Operation configures the path item schema for the HTTP path and method that the handler is registered to.

func (Doc) WithLicense

func (d Doc) WithLicense(l License) Doc

WithLicense declares the license information for the exposed API. Accepts a license-object.

func (Doc) WithServer

func (d Doc) WithServer(server Server) Doc

WithServer sets a server.

func (Doc) WithSummary

func (d Doc) WithSummary(summary string) Doc

WithSummary sets a short summary of the API to info-object.summary.

func (Doc) WithoutSecurities added in v0.0.7

func (d Doc) WithoutSecurities() Doc

WithoutSecurities includes an empty security requirement ({}) in Security Scheme Object.

type License added in v0.0.6

type License struct {
	Name string
	URL  string
}

License represents license-object.

type PathItemSpec

type PathItemSpec struct {
	// contains filtered or unexported fields
}

PathItemSpec represents the fields of a Path Item Object. [path-item-object]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-item-object

func (*PathItemSpec) AddRequest

func (o *PathItemSpec) AddRequest(body any, opts ...requestOption)

AddRequest configures operation request schema.

func (*PathItemSpec) AddResponse

func (o *PathItemSpec) AddResponse(body any, opts ...responseOption)

func (*PathItemSpec) SetId added in v0.0.9

func (o *PathItemSpec) SetId(id string)

func (*PathItemSpec) SetMethod

func (o *PathItemSpec) SetMethod(method string)

func (*PathItemSpec) SetPath

func (o *PathItemSpec) SetPath(path string)

func (*PathItemSpec) SetSummary

func (o *PathItemSpec) SetSummary(s string)

type PathItemSpecFunc

type PathItemSpecFunc func(o *PathItemSpec)

PathItemSpecFunc

func OperationMethod

func OperationMethod(method string) PathItemSpecFunc

OperationMethod

func OperationSummary

func OperationSummary(summary string) PathItemSpecFunc

OperationSummary

func PathItemSpecPath

func PathItemSpecPath(path string) PathItemSpecFunc

PathItemSpecPath

type Server added in v0.0.6

type Server struct {
	URL string
}

Server represents server.

Directories

Path Synopsis
Package internal
Package internal

Jump to

Keyboard shortcuts

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