gindocnic

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: MIT Imports: 8 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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"
	"io"
	"log"
	"net/http"
	"os"

	"github.com/alpdr/gindocnic"
	"github.com/gin-gonic/gin"
)

// Example
func main() {
	doc := gindocnic.MakeDoc().
		WithServer(gindocnic.Server{URL: "https://github.com/alpdr/gindocnic"}).
		WithOAuthAuthorizationCode("petStoreAuth", gindocnic.OAuthAuthorizationCode{
			AuthorizationURL: "https://auth.example.com/oauth/authorize",
			TokenURL:         "https://auth.example.com/oauth/token",
			Scopes:           map[string]string{"write:purchases": "Purchase pets"},
		}).
		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))
	r.POST("/purchases", doc.Operation(handler.purchase, handler.purchaseSpec))
	if err := doc.AssocRoutesInfo(r.Routes()); err != nil {
		log.Fatalf("%#v", err)
	}

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

	fmt.Print(string(yml))
}

type AddPetRequest struct {
	ID         int    `json:"id" binding:"required"`
	Name       string `json:"name" pattern:"^[a-zA-Z]+$"`
	Sex        string `json:"sex" binding:"oneof=male female"`
	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 PurchaseRequest struct {
	PetID    int `json:"petId" binding:"required"`
	Quantity int `json:"quantity" binding:"required"`
}

func (h *Handler) purchaseSpec(p *gindocnic.PathItemSpec) {
	p.SetSummary("Purchase a pet")
	p.AddRequest(PurchaseRequest{})
	p.AddResponse(Response{}, gindocnic.ResponseStatus(http.StatusCreated))
	p.AddResponse(ErrorResponse{}, gindocnic.ResponseStatus(http.StatusBadRequest))
	gindocnic.SetSecurity("petStoreAuth", []string{"write:purchases"})(p)
}
func (h *Handler) purchase(c *gin.Context) {}

type Handler struct{}
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: pets2
      parameters:
      - in: query
        name: name
        schema:
          type: string
      responses:
        "200":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GindocnicTestResponse'
          description: OK
        "404":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GindocnicTestErrorResponse'
          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:
              $ref: '#/components/schemas/GindocnicTestAddPetRequest'
      responses:
        "201":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GindocnicTestResponse'
          description: Created
        "400":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GindocnicTestErrorResponse'
          description: Bad Request
      summary: Add a new pet to the store
  /pets/{id}:
    get:
      operationId: petsid3
      parameters:
      - in: path
        name: id
        required: true
        schema:
          type: integer
      responses:
        "200":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GindocnicTestResponse'
          description: OK
        "404":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GindocnicTestErrorResponse'
          description: Not Found
      summary: Find a pet
  /purchases:
    post:
      operationId: purchases1
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GindocnicTestPurchaseRequest'
      responses:
        "201":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GindocnicTestResponse'
          description: Created
        "400":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GindocnicTestErrorResponse'
          description: Bad Request
      security:
      - petStoreAuth:
        - write:purchases
      summary: Purchase a pet
components:
  schemas:
    GindocnicTestAddPetRequest:
      properties:
        id:
          type: integer
        name:
          pattern: ^[a-zA-Z]+$
          type: string
        sex:
          enum:
          - male
          - female
          type: string
      required:
      - id
      type: object
    GindocnicTestErrorResponse:
      properties:
        error:
          type: string
      type: object
    GindocnicTestPurchaseRequest:
      properties:
        petId:
          type: integer
        quantity:
          type: integer
      required:
      - petId
      - quantity
      type: object
    GindocnicTestResponse:
      properties:
        id:
          type: integer
      type: object
  securitySchemes:
    petStoreAuth:
      flows:
        authorizationCode:
          authorizationUrl: https://auth.example.com/oauth/authorize
          scopes:
            write:purchases: Purchase pets
          tokenUrl: https://auth.example.com/oauth/token
      type: oauth2

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 ResponseBody added in v1.0.1

func ResponseBody(body any) responseOption

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) WithOAuthAuthorizationCode added in v1.3.0

func (d Doc) WithOAuthAuthorizationCode(name string, flow OAuthAuthorizationCode) Doc

WithOAuthAuthorizationCode registers an OAuth2 authorizationCode security scheme under the given name in components/securitySchemes.

func (Doc) WithOAuthClientCredentials added in v1.3.0

func (d Doc) WithOAuthClientCredentials(name string, flow OAuthClientCredentials) Doc

WithOAuthClientCredentials registers an OAuth2 clientCredentials security scheme under the given name in components/securitySchemes.

func (Doc) WithOpenAPIVersion added in v1.1.0

func (d Doc) WithOpenAPIVersion(version string) Doc

WithOpenAPIVersion sets the version of the OpenAPI Specification to openapi-object.openapi.

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 OAuthAuthorizationCode added in v1.3.0

type OAuthAuthorizationCode struct {
	AuthorizationURL string
	TokenURL         string
	Scopes           map[string]string
}

OAuthAuthorizationCode holds the required fields for the authorizationCode OAuth2 flow.

type OAuthClientCredentials added in v1.3.0

type OAuthClientCredentials struct {
	TokenURL string
	Scopes   map[string]string
}

OAuthClientCredentials holds the required fields for the clientCredentials OAuth2 flow.

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) SetDescription added in v1.1.0

func (o *PathItemSpec) SetDescription(s string)

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 OperationDescription added in v1.1.0

func OperationDescription(description string) PathItemSpecFunc

OperationDescription

func OperationID added in v1.2.0

func OperationID(id string) PathItemSpecFunc

OperationID sets the operation ID in the Operation Object.

func OperationMethod

func OperationMethod(method string) PathItemSpecFunc

OperationMethod

func OperationSummary

func OperationSummary(summary string) PathItemSpecFunc

OperationSummary

func PathItemSpecPath

func PathItemSpecPath(path string) PathItemSpecFunc

PathItemSpecPath

func SetSecurity added in v1.3.0

func SetSecurity(name string, scopes []string) PathItemSpecFunc

SetSecurity sets an operation-level security requirement, overriding the global default. Passing no scopes produces an empty scopes list for the named scheme.

type Server added in v0.0.6

type Server struct {
	URL string
}

Server represents server.

Jump to

Keyboard shortcuts

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