docs

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2021 License: MIT Imports: 15 Imported by: 1

README

docs

Automatically generate RESTful API documentation for GO projects - aligned with Open API Specification standard.

GolangCI Build Version Go Report Card Coverage Status codebeat badge Go Reference

go-OAS Docs converts structured OAS3 (Swagger3) objects into the Open API Specification & automatically serves it on chosen route and port. It's extremely flexible and simple, so basically it can be integrated into any framework or existing project.

Getting Started

  1. Download docs by using:
    $ go get -u github.com/go-oas/docs
    
  2. Add one line annotation to the handler you wish to use in the following format: // @OAS <FUNC_NAME> <ROUTE> <HTTP_METHOD> Examples:
    // @OAS handleCreateUser /users POST
    // @OAS handleGetUser /users GET
    
  3. Declare all required documentation elements that are shared. Or reuse ones that already exist in the examples directory.
  4. Declare specific docs elements per route.

How to use

For more explicit example, please refer to docs/examples

Add OAS TAG to your existing handler that handles fetching of a User:

package users

import "net/http"

// @OAS handleGetUser /users GET
func (s *service) handleGetUser() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
	}
}

Create a unique API documentation function for that endpoint:

package main

import "github.com/go-oas/docs"

func handleGetUserRoute(oasPathIndex int, oas *docs.OAS) {
	path := oas.GetPathByIndex(oasPathIndex)

	path.Summary = "Get a User"
	path.OperationID = "getUser"
	path.RequestBody = docs.RequestBody{}
	path.Responses = docs.Responses{
		getResponseOK(),
	}

	path.Tags = append(path.Tags, "pet")
}

Bear in mind that creating a unique function per endpoint handler is not required, but simply provides good value in usability of shared documentation elements.

Once you created the function, simply register it for parsing by using AttachRoutes() defined upon OAS structure. E.g.:


package main

import (
	"github.com/go-oas/docs"
)

func main() {
	apiDoc := docs.New()
	apiDoc.AttachRoutes([]interface{}{
		handleGetUserRoute,
	})

If this approach is too flexible for you, you are always left with the possibility to create your own attacher - or any other parts of the system for that matter.

Examples

To run examples, and checkout hosted documentation via Swagger UI, issue the following command:

$ go run ./examples/*.go

And navigate to http://localhost:3005/docs/api/ in case that you didn't change anything before running the example above.


Roadmap & Project board

Check out the current Project board for more information about the first alpha release. Note: Board & project are still in its early phase.

You can join projects Telegram group at: https://t.me/go_oas

Documentation

Index

Constants

View Source
const (
	OASAnnotationInit = "// @OAS "
)

Variables

This section is empty.

Functions

func ServeSwaggerUI

func ServeSwaggerUI(conf *ConfigSwaggerUI) error

ServeSwaggerUI does what its name implies - runs Swagger UI on mentioned set port and route.

Types

type Component

type Component struct {
	Schemas         Schemas         `yaml:"schemas"`
	SecuritySchemes SecuritySchemes `yaml:"securitySchemes"`
}

type Components

type Components []Component

type ConfigBuilder

type ConfigBuilder struct {
	CustomPath string
}

ConfigBuilder represents a config structure which will be used for the YAML Builder (BuildDocs fn).

This structure was introduced to enable possible extensions to the OAS.BuildDocs() without introducing breaking API changes.

type ConfigSwaggerUI

type ConfigSwaggerUI struct {
	Route string
	Port  string
	// contains filtered or unexported fields
}

type Contact

type Contact struct {
	Email string `yaml:"email"`
}

type ContentType

type ContentType struct {
	Name   string `yaml:"ct-name"`   // e.g. application/json
	Schema string `yaml:"ct-schema"` // e.g. $ref: '#/components/schemas/Pet'
}

type ContentTypes

type ContentTypes []ContentType

type ExternalDocs

type ExternalDocs struct {
	Description string `yaml:"description"`
	URL         URL    `yaml:"url"`
}

type Info

type Info struct {
	Title          string  `yaml:"title"`
	Description    string  `yaml:"description"`
	TermsOfService URL     `yaml:"termsOfService"`
	Contact        Contact `yaml:"contact"`
	License        License `yaml:"license"`
	Version        Version `yaml:"version"`
}

func (*Info) SetContact

func (i *Info) SetContact(email string)

SetContact setts the contact on the Info struct.

func (*Info) SetLicense

func (i *Info) SetLicense(licType, url string)

SetLicense sets the license on the Info struct.

type License

type License struct {
	Name string `yaml:"name"`
	URL  URL    `yaml:"url"`
}

type OAS

type OAS struct {
	OASVersion       OASVersion   `yaml:"openapi"`
	Info             Info         `yaml:"info"`
	ExternalDocs     ExternalDocs `yaml:"externalDocs"`
	Servers          Servers      `yaml:"servers"`
	Tags             Tags         `yaml:"tags"`
	Paths            Paths        `yaml:"paths"`
	Components       Components   `yaml:"components"`
	RegisteredRoutes RegRoutes    `yaml:"-"`
}

OAS - represents Open API Specification structure, in its approximated Go form.

func New

func New() OAS

func (*OAS) AttachRoutes

func (o *OAS) AttachRoutes(fns []interface{})

func (*OAS) BuildDocs

func (o *OAS) BuildDocs(conf ...ConfigBuilder) error

BuildDocs marshals the OAS struct to YAML and saves it to the chosen output file.

Returns an error if there is any.

func (*OAS) Call

func (o *OAS) Call(name string, params ...interface{}) (result []reflect.Value, err error)

func (*OAS) GetInfo

func (o *OAS) GetInfo() *Info

GetInfo returns pointer to the Info struct.

func (*OAS) GetPathByIndex

func (o *OAS) GetPathByIndex(index int) *Path

func (*OAS) GetRegisteredRoutes

func (o *OAS) GetRegisteredRoutes() RegRoutes

func (*OAS) MapAnnotationsInPath

func (o *OAS) MapAnnotationsInPath(scanIn string, conf ...configAnnotation) error

MapAnnotationsInPath scanIn is relevant from initiator calling it.

It accepts the path in which to scan for annotations within Go files.

func (*OAS) SetOASVersion

func (o *OAS) SetOASVersion(ver string)

SetOASVersion sets the OAS version, by casting string to OASVersion type.

type OASVersion

type OASVersion Version

Version is represented in SemVer format.

type Path

type Path struct {
	Route           string           `yaml:"route"`
	HTTPMethod      string           `yaml:"httpMethod"`
	Tags            []string         `yaml:"tags"`
	Summary         string           `yaml:"summary"`
	OperationID     string           `yaml:"operationId"`
	RequestBody     RequestBody      `yaml:"requestBody"`
	Responses       Responses        `yaml:"responses"`
	Security        SecurityEntities `yaml:"security,omitempty"`
	HandlerFuncName string           `yaml:"-"`
}

type Paths

type Paths []Path

type RegRoutes

type RegRoutes map[string]interface{}

type RequestBody

type RequestBody struct {
	Description string       `yaml:"description"`
	Content     ContentTypes `yaml:"content"`
	Required    bool         `yaml:"required"`
}

type Response

type Response struct {
	Code        uint         `yaml:"code"`
	Description string       `yaml:"description"`
	Content     ContentTypes `yaml:"content"`
}

type Responses

type Responses []Response

type Schema

type Schema struct {
	Name       string
	Type       string
	Properties SchemaProperties
	XML        XMLEntry `yaml:"xml, omitempty"`
	Ref        string   // $ref: '#/components/schemas/Pet' // TODO: Should this be omitted if empty?
}

type SchemaProperties

type SchemaProperties []SchemaProperty

type SchemaProperty

type SchemaProperty struct {
	Name        string      `yaml:"-"`
	Type        string      // OAS3.0 data types - e.g. integer, boolean, string
	Format      string      `yaml:"format,omitempty"`
	Description string      `yaml:"description,omitempty"`
	Enum        []string    `yaml:"enum,omitempty"`
	Default     interface{} `yaml:"default,omitempty"`
}

type Schemas

type Schemas []Schema

type Security

type Security struct {
	AuthName  string
	PermTypes []string // write:pets , read:pets etc.
}

type SecurityEntities

type SecurityEntities []Security

type SecurityFlow

type SecurityFlow struct {
	Type    string         `yaml:"type,omitempty"`
	AuthURL URL            `yaml:"authorizationUrl,omitempty"`
	Scopes  SecurityScopes `yaml:"scopes,omitempty"`
}

type SecurityFlows

type SecurityFlows []SecurityFlow

type SecurityScheme

type SecurityScheme struct {
	Name  string        `yaml:"name,omitempty"`
	Type  string        `yaml:"type,omitempty"`
	In    string        `yaml:"in,omitempty"`
	Flows SecurityFlows `yaml:"flows,omitempty"`
}

type SecuritySchemes

type SecuritySchemes []SecurityScheme

type SecurityScope

type SecurityScope struct {
	Name        string `yaml:"name,omitempty"`
	Description string `yaml:"description,omitempty"`
}

type SecurityScopes

type SecurityScopes []SecurityScope

type Server

type Server struct {
	URL URL `yaml:"url"`
}

type Servers

type Servers []Server

type Tag

type Tag struct {
	Name         string       `yaml:"name"`
	Description  string       `yaml:"description"`
	ExternalDocs ExternalDocs `yaml:"externalDocs"`
}

type Tags

type Tags []Tag

func (*Tags) AppendTag

func (tt *Tags) AppendTag(tag *Tag)

func (*Tags) SetTag

func (tt *Tags) SetTag(name, tagDescription string, extDocs ExternalDocs)

type URL

type URL string

Version is represented in SemVer format.

type Version

type Version string

Version is represented in SemVer format.

type XMLEntry

type XMLEntry struct {
	Name string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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