swgen

package module
v0.6.28 Latest Latest
Warning

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

Go to latest
Published: May 31, 2021 License: Apache-2.0 Imports: 17 Imported by: 2

README

Swagger Generator (swgen)

Build Status Coverage Status GoDoc

Swagger Generator is a library which helps to generate Swagger Specification in JSON format on-the-fly.

OpenAPI 3.0 Support

OpenAPI 3.0 support is available with openapi3.Reflector.

// Add OpenAPI 3.0 reflector to enable proxying to OpenAPI 3.0 Schema.
openapi3Reflector := openapi3.Reflector{}
gen.SetOAS3Proxy(&openapi3Reflector)

Installation

You can use go get to install the swgen package

go get github.com/swaggest/swgen

Then import it into your own code

import "github.com/swaggest/swgen"

Example

package main

import (
    "fmt"

    "github.com/swaggest/swgen"
)

// PetsRequest defines all params for /pets request
type PetsRequest struct {
    Tags  []string `schema:"tags" in:"query" required:"-" description:"tags to filter by"`
    Limit int32    `schema:"limit" in:"query" required:"-" description:"maximum number of results to return"`
}

// Pet contains information of a pet
type Pet struct {
    ID   int64  `json:"id"`
    Name string `json:"name"`
    Tag  string `json:"tag"`
}

func main() {
	gen := swgen.NewGenerator()
	gen.SetHost("petstore.swagger.io").SetBasePath("/api")
	gen.SetInfo("Swagger Petstore (Simple)", "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", "http://helloreverb.com/terms/", "2.0")
	gen.SetLicense("MIT", "http://opensource.org/licenses/MIT")
	gen.SetContact("Swagger API team", "http://swagger.io", "foo@example.com")
	gen.AddSecurityDefinition("BasicAuth", swgen.SecurityDef{Type: swgen.SecurityBasicAuth})

	pathInf := swgen.PathItemInfo{
		Path:        "/pets",
		Method:      "GET",
		Title:       "findPets",
		Description: "Returns all pets from the system that the user has access to",
		Tag:         "v1",
		Deprecated:  false,
		Security:    []string{"BasicAuth"},
		Request:     new(PetsRequest), // request object
		Response:    new([]Pet),       // response object
	}
	pathInf.AddExtendedField("x-example", "example")

	gen.SetPathItem(pathInf)

	// extended field
	gen.AddExtendedField("x-uppercase-version", true)

	docData, _ := gen.GenDocument()
	fmt.Println(string(docData))

	// output:
	// {"swagger":"2.0","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"2.0"},"host":"petstore.swagger.io","basePath":"/api","schemes":["http","https"],"paths":{"/pets":{"get":{"tags":["v1"],"summary":"findPets","description":"Returns all pets from the system that the user has access to","parameters":[{"description":"tags to filter by","type":"array","name":"tags","in":"query","items":{"type":"string"},"collectionFormat":"multi"},{"description":"maximum number of results to return","type":"integer","format":"int32","name":"limit","in":"query"}],"responses":{"200":{"description":"OK","schema":{"type":"array","items":{"$ref":"#/definitions/Pet"}}}},"security":[{"BasicAuth":[]}],"x-example":"example"}}},"definitions":{"Pet":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}},"securityDefinitions":{"BasicAuth":{"type":"basic"}},"x-uppercase-version":true}
}

License

Distributed under the Apache License, version 2.0. Please see license file in code for more details.

Documentation

Overview

Package swgen (Swagger Generator) is a library which helps to generate [Swagger Specification](http://swagger.io/specification/) in JSON format on-the-fly.

Index

Examples

Constants

View Source
const (
	// SecurityBasicAuth is a HTTP Basic Authentication security type.
	SecurityBasicAuth securityType = "basic"
	// SecurityAPIKey is an API key security type.
	SecurityAPIKey securityType = "apiKey"
	// SecurityOAuth2 is an OAuth2 security type.
	SecurityOAuth2 securityType = "oauth2"
	// SecurityBearerToken is a HTTP Bearer token security type.
	SecurityBearerToken = "bearer"
)
View Source
const (
	// APIKeyInHeader defines API key in header.
	APIKeyInHeader apiKeyIn = "header"
	// APIKeyInQuery defines API key in query parameter.
	APIKeyInQuery apiKeyIn = "query"
)
View Source
const (
	// Oauth2AccessCode is access code Oauth2 flow.
	Oauth2AccessCode oauthFlow = "accessCode"
	// Oauth2Application is application Oauth2 flow.
	Oauth2Application oauthFlow = "application"
	// Oauth2Implicit is implicit Oauth2 flow.
	Oauth2Implicit oauthFlow = "implicit"
	// Oauth2Password is password Oauth2 flow.
	Oauth2Password oauthFlow = "password"
)

Variables

This section is empty.

Functions

func JSONSchemaInterceptType added in v0.6.21

func JSONSchemaInterceptType(v reflect.Value, s *jsonschema.Schema) (bool, error)

JSONSchemaInterceptType is an adapter for github.com/swaggest/jsonschema-go.

func LoadJSONSchemaFromSwgen added in v0.6.21

func LoadJSONSchemaFromSwgen(d SwaggerData, s *jsonschema.Schema)

LoadJSONSchemaFromSwgen is an adapter for github.com/swaggest/jsonschema-go.

Types

type CommonFields added in v0.5.1

type CommonFields struct {
	Title       string      `json:"title,omitempty"`
	Description string      `json:"description,omitempty"`
	Default     interface{} `json:"default,omitempty"`

	// Type is defined with reflection.
	Type string `json:"type,omitempty"`

	Pattern string `json:"pattern,omitempty"`
	Format  string `json:"format,omitempty"`

	MultipleOf float64  `json:"multipleOf,omitempty"`
	Maximum    *float64 `json:"maximum,omitempty"`
	Minimum    *float64 `json:"minimum,omitempty"`

	MaxLength     *int64 `json:"maxLength,omitempty"`
	MinLength     *int64 `json:"minLength,omitempty"`
	MaxItems      *int64 `json:"maxItems,omitempty"`
	MinItems      *int64 `json:"minItems,omitempty"`
	MaxProperties *int64 `json:"maxProperties,omitempty"`
	MinProperties *int64 `json:"minProperties,omitempty"`

	ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"`
	ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"`
	UniqueItems      bool `json:"uniqueItems,omitempty"`

	// Enum defines value enumeration.
	//
	// Can be populated from
	//   NamedEnum() ([]interface{}, []string)
	// or
	//   Enum() []interface{}
	//
	// Can be imported from tag `enum`.
	Enum
}

CommonFields keeps fields shared between ParamObj and SchemaObj.

JSON Schema tags

Values can be populated from field tags of original field:

type MyObj struct {
   BoundedNumber `query:"boundedNumber" minimum:"-100" maximum:"100"`
   SpecialString `json:"specialString" pattern:"^[a-z]{4}$" minLength:"4" maxLength:"4"`
}

These tags can be used:

type ContactObj

type ContactObj struct {
	Name  string `json:"name"`
	URL   string `json:"url,omitempty"`
	Email string `json:"email,omitempty"`
}

ContactObj contains contact information for the exposed API.

type Document

type Document struct {
	Version             string                 `json:"swagger"`                       // Specifies the Swagger Specification version being used
	Info                InfoObj                `json:"info"`                          // Provides metadata about the API
	Host                string                 `json:"host,omitempty"`                // The host (name or ip) serving the API
	BasePath            string                 `json:"basePath,omitempty"`            // The base path on which the API is served, which is relative to the host
	Schemes             []string               `json:"schemes,omitempty"`             // Values MUST be from the list: "http", "https", "ws", "wss"
	Paths               map[string]PathItem    `json:"paths"`                         // The available paths and operations for the API
	Definitions         map[string]SchemaObj   `json:"definitions,omitempty"`         // An object to hold data types produced and consumed by operations
	SecurityDefinitions map[string]SecurityDef `json:"securityDefinitions,omitempty"` // An object to hold available security mechanisms
	// contains filtered or unexported fields
}

Document represent for a document object of swagger data, see http://swagger.io/specification/.

func (*Document) AddExtendedField

func (ad *Document) AddExtendedField(name string, value interface{})

AddExtendedField add field to additional data map.

func (Document) MarshalJSON

func (s Document) MarshalJSON() ([]byte, error)

MarshalJSON marshal Document with additionalData inlined.

type Enum

type Enum struct {
	Enum      []interface{} `json:"enum,omitempty"`
	EnumNames []string      `json:"x-enum-names,omitempty"`
}

Enum can be use for sending Enum data that need validate.

func (*Enum) LoadFromField added in v0.4.2

func (enum *Enum) LoadFromField(field reflect.StructField)

LoadFromField loads enum from field tag: json array or comma-separated string.

type Generator

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

Generator create swagger document.

func NewGenerator

func NewGenerator() *Generator

NewGenerator create a new Generator.

func (*Generator) AddDefaultResponse

func (g *Generator) AddDefaultResponse(httpCode int, response interface{})

AddDefaultResponse adds http code and response structure that will be applied to all operations.

func (*Generator) AddExtendedField

func (g *Generator) AddExtendedField(name string, value interface{}) *Generator

AddExtendedField add vendor extension field to document.

func (*Generator) AddPackagePrefix added in v0.5.2

func (g *Generator) AddPackagePrefix(enabled bool) *Generator

AddPackagePrefix controls prefixing definition name with package. With option enabled type `some/package.Entity` will have "PackageEntity" key in definitions, "Entity" otherwise.

func (*Generator) AddSecurityDefinition

func (g *Generator) AddSecurityDefinition(name string, def SecurityDef) *Generator

AddSecurityDefinition adds shared security definition to document.

func (*Generator) AddTypeMap

func (g *Generator) AddTypeMap(source interface{}, destination interface{}) *Generator

AddTypeMap adds mapping relation to treat values of same type as source as they were of same type as destination.

Example
package main

import (
	"net/http"

	"github.com/swaggest/swgen"
	"github.com/swaggest/swgen/internal/sample/experiment"
)

func main() {
	// If you don't have control or don't want to modify a type,
	// you can alias it and implement definition alteration on alias.
	type experimentEntity experiment.Entity

	gen := swgen.NewGenerator()

	// Then you can map original type to your alias in Generator instance
	gen.AddTypeMap(new(experiment.Entity), new(experimentEntity))

	gen.AddTypeMap(new(experiment.Data), swgen.SchemaDefinitionFunc(func() swgen.SwaggerData {
		def := swgen.SwaggerData{}
		def.TypeName = "experimentData"

		return def
	}))

	info := swgen.PathItemInfo{
		Method:   http.MethodPost,
		Path:     "/any",
		Request:  new(experiment.Data),
		Response: new(experiment.Entity),
	}
	gen.SetPathItem(info)
}
Output:

func (*Generator) CapitalizeDefinitions added in v0.6.2

func (g *Generator) CapitalizeDefinitions(enabled bool) *Generator

CapitalizeDefinitions enables first char capitalization for definition names. With option enabled type `some/package.entity` will have "Entity" key in definitions, "entity" otherwise.

func (*Generator) Document

func (g *Generator) Document() Document

Document is an accessor to generated document.

func (*Generator) EnableCORS

func (g *Generator) EnableCORS(b bool, allowHeaders ...string) *Generator

EnableCORS enable HTTP handler support CORS.

func (*Generator) GenDocument

func (g *Generator) GenDocument() ([]byte, error)

GenDocument returns document specification in JSON string (in []byte).

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/swaggest/openapi-go/openapi3"
	"github.com/swaggest/swgen"
)

func main() {
	// PetsRequest defines all params for /pets request
	type PetsRequest struct {
		Tags  []string `query:"tags"  description:"tags to filter by"`
		Limit int32    `query:"limit" description:"maximum number of results to return"`
	}

	// Pet contains information of a pet
	type Pet struct {
		ID   int64  `json:"id"`
		Name string `json:"name"`
		Tag  string `json:"tag"`
	}

	gen := swgen.NewGenerator()

	// Add OpenAPI 3.0 reflector to enable proxying to OpenAPI 3.0 Schema.
	openapi3Reflector := openapi3.Reflector{}
	gen.SetOAS3Proxy(&openapi3Reflector)

	gen.SetHost("petstore.swagger.io").SetBasePath("/api")
	gen.SetInfo("Swagger Petstore (Simple)", "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", "http://helloreverb.com/terms/", "2.0")
	gen.SetLicense("MIT", "http://opensource.org/licenses/MIT")
	gen.SetContact("Swagger API team", "http://swagger.io", "foo@example.com")
	gen.AddSecurityDefinition("BasicAuth", swgen.SecurityDef{Type: swgen.SecurityBasicAuth})

	pathInf := swgen.PathItemInfo{
		Path:        "/pets",
		Method:      "GET",
		Title:       "findPets",
		Description: "Returns all pets from the system that the user has access to",
		Tag:         "v1",
		Deprecated:  false,
		Security:    []string{"BasicAuth"},
		Request:     new(PetsRequest), // request object
		Response:    new([]Pet),       // response object
	}
	pathInf.AddExtendedField("x-example", "example")

	gen.SetPathItem(pathInf)

	// extended field
	gen.AddExtendedField("x-uppercase-version", true)

	docData, _ := gen.GenDocument()
	fmt.Println(string(docData))

	openapi3Data, _ := json.Marshal(openapi3Reflector.Spec)
	fmt.Println(string(openapi3Data))

}
Output:

{"swagger":"2.0","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"2.0"},"host":"petstore.swagger.io","basePath":"/api","schemes":["http","https"],"paths":{"/pets":{"get":{"tags":["v1"],"summary":"findPets","description":"Returns all pets from the system that the user has access to","parameters":[{"description":"tags to filter by","type":"array","name":"tags","in":"query","items":{"type":"string"},"collectionFormat":"multi"},{"description":"maximum number of results to return","type":"integer","format":"int32","name":"limit","in":"query"}],"responses":{"200":{"description":"OK","schema":{"type":"array","items":{"$ref":"#/definitions/Pet"}}}},"security":[{"BasicAuth":[]}],"x-example":"example"}}},"definitions":{"Pet":{"type":"object","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"},"tag":{"type":"string"}}}},"securityDefinitions":{"BasicAuth":{"type":"basic"}},"x-uppercase-version":true}
{"openapi":"3.0.3","info":{"title":"Swagger Petstore (Simple)","description":"A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification","termsOfService":"http://helloreverb.com/terms/","contact":{"name":"Swagger API team","url":"http://swagger.io","email":"foo@example.com"},"license":{"name":"MIT","url":"http://opensource.org/licenses/MIT"},"version":"2.0"},"servers":[{"url":"http://petstore.swagger.io/api"}],"paths":{"/pets":{"get":{"tags":["v1"],"summary":"findPets","description":"Returns all pets from the system that the user has access to","parameters":[{"name":"tags","in":"query","description":"tags to filter by","schema":{"type":"array","items":{"type":"string"},"description":"tags to filter by"}},{"name":"limit","in":"query","description":"maximum number of results to return","schema":{"type":"integer","description":"maximum number of results to return"}}],"responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/SwgenTestPet"}}}}}},"security":[{"BasicAuth":[]}]}}},"components":{"schemas":{"SwgenTestPet":{"type":"object","properties":{"id":{"type":"integer"},"name":{"type":"string"},"tag":{"type":"string"}}}},"securitySchemes":{"BasicAuth":{"type":"http","scheme":"basic"}}},"x-uppercase-version":true}

func (*Generator) GetJSONSchemaRequestBody added in v0.6.4

func (g *Generator) GetJSONSchemaRequestBody(op *OperationObj, cfg ...JSONSchemaConfig) (map[string]interface{}, error)

GetJSONSchemaRequestBody returns returns request body schema if any.

func (*Generator) GetJSONSchemaRequestGroups

func (g *Generator) GetJSONSchemaRequestGroups(op *OperationObj, cfg ...JSONSchemaConfig) (map[string]ObjectJSONSchema, error)

GetJSONSchemaRequestGroups returns a map of object schemas converted from parameters (excluding in body), grouped by in.

func (*Generator) IndentJSON

func (g *Generator) IndentJSON(enabled bool) *Generator

IndentJSON controls JSON indentation.

func (*Generator) JSONSchema

func (g *Generator) JSONSchema(s SchemaObj, option ...JSONSchemaConfig) (map[string]interface{}, error)

JSONSchema builds JSON Schema for Swagger Schema object.

func (*Generator) ParamJSONSchema

func (g *Generator) ParamJSONSchema(p ParamObj, cfg ...JSONSchemaConfig) (map[string]interface{}, error)

ParamJSONSchema builds JSON Schema for Swagger Parameter object.

func (*Generator) ParseDefinition

func (g *Generator) ParseDefinition(i interface{}) SchemaObj

ParseDefinition create a DefObj from input object, it should be a non-nil pointer to anything it reuse schema/json tag for property name.

func (*Generator) ParseParameters

func (g *Generator) ParseParameters(i interface{}) (string, []ParamObj)

ParseParameters parse input struct to swagger parameter object.

func (*Generator) ReflectGoTypes

func (g *Generator) ReflectGoTypes(enabled bool) *Generator

ReflectGoTypes controls JSON indentation.

func (*Generator) ResetDefinitions

func (g *Generator) ResetDefinitions()

ResetDefinitions will remove all exists definitions and init again.

func (*Generator) ResetPaths

func (g *Generator) ResetPaths()

ResetPaths remove all current paths.

func (*Generator) ServeHTTP

func (g *Generator) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler to server swagger.json document.

func (*Generator) SetBasePath

func (g *Generator) SetBasePath(basePath string) *Generator

SetBasePath set host info for swagger specification.

func (*Generator) SetContact

func (g *Generator) SetContact(name, url, email string) *Generator

SetContact set contact information for API.

func (*Generator) SetHost

func (g *Generator) SetHost(host string) *Generator

SetHost set host info for swagger specification.

func (*Generator) SetInfo

func (g *Generator) SetInfo(title, description, term, version string) *Generator

SetInfo set information about API.

func (*Generator) SetLicense

func (g *Generator) SetLicense(name, url string) *Generator

SetLicense set license information for API.

func (*Generator) SetOAS3Proxy added in v0.6.21

func (g *Generator) SetOAS3Proxy(oas3Proxy *openapi3.Reflector)

SetOAS3Proxy enables OpenAPI3 spec collection with provided reflector.

func (*Generator) SetPathItem

func (g *Generator) SetPathItem(info PathItemInfo) *OperationObj

SetPathItem register path item with some information and input, output.

func (*Generator) WalkJSONSchemaRequestBodies added in v0.6.4

func (g *Generator) WalkJSONSchemaRequestBodies(function func(path, method string, schema map[string]interface{})) error

WalkJSONSchemaRequestBodies iterates over all request bodies.

func (*Generator) WalkJSONSchemaRequestGroups

func (g *Generator) WalkJSONSchemaRequestGroups(function func(path, method, in string, schema ObjectJSONSchema)) error

WalkJSONSchemaRequestGroups iterates over all request parameters grouped by path, method and in into an instance of JSON Schema.

func (*Generator) WalkJSONSchemaResponses

func (g *Generator) WalkJSONSchemaResponses(function func(path, method string, statusCode int, schema map[string]interface{})) error

WalkJSONSchemaResponses iterates over all responses grouped by path, method and status code into an instance of JSON Schema.

type InfoObj

type InfoObj struct {
	Title          string     `json:"title"` // The title of the application
	Description    string     `json:"description"`
	TermsOfService string     `json:"termsOfService"`
	Contact        ContactObj `json:"contact"`
	License        LicenseObj `json:"license"`
	Version        string     `json:"version"`
}

InfoObj provides metadata about the API.

type JSONSchemaConfig

type JSONSchemaConfig struct {
	CollectDefinitions map[string]map[string]interface{}
	StripDefinitions   bool
	DefinitionsPrefix  string
}

JSONSchemaConfig is optional JSON schema rendering configuration.

type LicenseObj

type LicenseObj struct {
	Name string `json:"name"`
	URL  string `json:"url,omitempty"`
}

LicenseObj license information for the exposed API.

type ObjectJSONSchema

type ObjectJSONSchema struct {
	ID         string                            `json:"id,omitempty"`
	Schema     string                            `json:"$schema,omitempty"`
	Type       string                            `json:"type"`
	Required   []string                          `json:"required,omitempty"`
	Properties map[string]map[string]interface{} `json:"properties"`
}

ObjectJSONSchema is a simplified JSON Schema for object.

func (ObjectJSONSchema) ToMap

func (o ObjectJSONSchema) ToMap() (map[string]interface{}, error)

ToMap converts ObjectJSONSchema to a map.

type OperationObj

type OperationObj struct {
	Tags        []string              `json:"tags,omitempty"`
	Summary     string                `json:"summary"`     // like a title, a short summary of what the operation does (120 chars)
	Description string                `json:"description"` // A verbose explanation of the operation behavior
	Parameters  []ParamObj            `json:"parameters,omitempty"`
	Produces    []string              `json:"produces,omitempty"`
	Consumes    []string              `json:"consumes,omitempty"`
	Responses   Responses             `json:"responses"`
	Security    []map[string][]string `json:"security,omitempty"`
	Deprecated  bool                  `json:"deprecated,omitempty"`
	// contains filtered or unexported fields
}

OperationObj describes a single API operation on a path, see http://swagger.io/specification/#operationObject.

func (*OperationObj) AddExtendedField

func (ad *OperationObj) AddExtendedField(name string, value interface{})

AddExtendedField add field to additional data map.

func (OperationObj) MarshalJSON

func (o OperationObj) MarshalJSON() ([]byte, error)

MarshalJSON marshal OperationObj with additionalData inlined.

type ParamItemObj

type ParamItemObj struct {
	CommonFields
	Items            *ParamItemObj `json:"items,omitempty"`            // Required if type is "array"
	CollectionFormat string        `json:"collectionFormat,omitempty"` // "multi" - this is valid only for parameters in "query" or "formData"
}

ParamItemObj describes an property object, in param object or property of definition, see http://swagger.io/specification/#itemsObject.

type ParamObj

type ParamObj struct {
	CommonFields
	Name   string        `json:"name,omitempty"`
	In     string        `json:"in,omitempty"`     // Possible values are "query", "header", "path", "formData" or "body"
	Items  *ParamItemObj `json:"items,omitempty"`  // Required if type is "array"
	Schema *SchemaObj    `json:"schema,omitempty"` // Required if type is "body"

	// CollectionFormat defines serialization:
	// "multi" is valid only for parameters in "query" or "formData": foo=value&foo=another_value
	// "csv" is comma-separated values: "foo,bar,baz"
	// "ssv" is space-separated values: "foo bar baz"
	// "tsv" is tab-separated values: "foo\tbar\tbaz"
	// "pipes" is pipe-separated values: "foo|bar|baz"
	CollectionFormat string `json:"collectionFormat,omitempty"`

	Required bool `json:"required,omitempty"`
	// contains filtered or unexported fields
}

ParamObj describes a single operation parameter, see http://swagger.io/specification/#parameterObject.

func (*ParamObj) AddExtendedField

func (ad *ParamObj) AddExtendedField(name string, value interface{})

AddExtendedField add field to additional data map.

func (ParamObj) MarshalJSON

func (o ParamObj) MarshalJSON() ([]byte, error)

MarshalJSON marshal ParamObj with additionalData inlined.

type PathItem

type PathItem struct {
	Ref     string        `json:"$ref,omitempty"`
	Get     *OperationObj `json:"get,omitempty"`
	Put     *OperationObj `json:"put,omitempty"`
	Post    *OperationObj `json:"post,omitempty"`
	Delete  *OperationObj `json:"delete,omitempty"`
	Options *OperationObj `json:"options,omitempty"`
	Head    *OperationObj `json:"head,omitempty"`
	Patch   *OperationObj `json:"patch,omitempty"`
	Params  *ParamObj     `json:"parameters,omitempty"`
}

PathItem describes the operations available on a single path, see http://swagger.io/specification/#pathItemObject.

func (PathItem) HasMethod

func (pi PathItem) HasMethod(method string) bool

HasMethod returns true if in path item already have operation for given method.

func (PathItem) Map

func (pi PathItem) Map() map[string]*OperationObj

Map returns operations mapped by HTTP method.

type PathItemInfo

type PathItemInfo struct {
	Path        string
	Method      string
	Title       string
	Description string
	Tag         string
	Deprecated  bool

	// Request holds a sample of request structure, e.g. new(MyRequest).
	Request interface{}

	// Output holds a sample of successful response, e.g. new(MyResponse).
	Response interface{}

	// MIME types of input and output
	Produces []string
	Consumes []string

	Security       []string            // Names of security definitions.
	SecurityOAuth2 map[string][]string // Map of names of security definitions to required scopes.

	SuccessfulResponseCode int
	// contains filtered or unexported fields
}

PathItemInfo some basic information of a path item and operation object.

func (*PathItemInfo) AddExtendedField

func (ad *PathItemInfo) AddExtendedField(name string, value interface{})

AddExtendedField add field to additional data map.

func (*PathItemInfo) AddResponse

func (p *PathItemInfo) AddResponse(statusCode int, output interface{}) *PathItemInfo

AddResponse adds response with http status code and output structure.

func (*PathItemInfo) AddResponses

func (p *PathItemInfo) AddResponses(responses ...WithStatusCode)

AddResponses adds multiple responses with WithStatusCode.

func (*PathItemInfo) RemoveResponse

func (p *PathItemInfo) RemoveResponse(statusCode int) bool

RemoveResponse removes response with http status code and returns if it existed.

func (*PathItemInfo) Responses added in v0.6.18

func (p *PathItemInfo) Responses() map[int]interface{}

Responses returns additional responses.

type ResponseObj

type ResponseObj struct {
	Ref         string      `json:"$ref,omitempty"`
	Description string      `json:"description,omitempty"`
	Schema      *SchemaObj  `json:"schema,omitempty"`
	Headers     interface{} `json:"headers,omitempty"`
	Examples    interface{} `json:"examples,omitempty"`
}

ResponseObj describes a single response from an API Operation.

type Responses

type Responses map[int]ResponseObj

Responses list of response object.

type SchemaDefinition

type SchemaDefinition interface {
	SwaggerDef() SwaggerData
}

SchemaDefinition allows to return custom definitions.

type SchemaDefinitionFunc added in v0.5.0

type SchemaDefinitionFunc func() SwaggerData

SchemaDefinitionFunc is a helper to return custom definitions.

func (SchemaDefinitionFunc) SwaggerDef added in v0.5.0

func (f SchemaDefinitionFunc) SwaggerDef() SwaggerData

SwaggerDef returns custom definition.

type SchemaObj

type SchemaObj struct {
	CommonFields
	Ref                  string               `json:"$ref,omitempty"`
	Items                *SchemaObj           `json:"items,omitempty"`                // if type is array
	AdditionalProperties *SchemaObj           `json:"additionalProperties,omitempty"` // if type is object (map[])
	Required             []string             `json:"required,omitempty"`
	Properties           map[string]SchemaObj `json:"properties,omitempty"` // if type is object
	Example              interface{}          `json:"example,omitempty"`
	Nullable             bool                 `json:"x-nullable,omitempty"`
	TypeName             string               `json:"-"` // for internal using, passing typeName
	GoType               string               `json:"x-go-type,omitempty"`
	GoPropertyNames      map[string]string    `json:"x-go-property-names,omitempty"`
	GoPropertyTypes      map[string]string    `json:"x-go-property-types,omitempty"`
	// contains filtered or unexported fields
}

SchemaObj describes a schema for json format.

func NewSchemaObj

func NewSchemaObj(jsonType, typeName string) (so *SchemaObj)

NewSchemaObj Constructor function for SchemaObj struct type.

func (*SchemaObj) AddExtendedField

func (ad *SchemaObj) AddExtendedField(name string, value interface{})

AddExtendedField add field to additional data map.

func (SchemaObj) Export

func (o SchemaObj) Export() SchemaObj

Export returns a "schema reference object" corresponding to this schema object. A "schema reference object" is an abridged version of the original SchemaObj, having only two non-empty fields: Ref and TypeName. "SwaggerData reference objects" are used to refer original schema objects from other schemas.

func (SchemaObj) MarshalJSON

func (o SchemaObj) MarshalJSON() ([]byte, error)

MarshalJSON marshal SchemaObj with additionalData inlined.

type SecurityDef

type SecurityDef struct {
	Type securityType `json:"type"`

	// apiKey properties.
	In   apiKeyIn `json:"in,omitempty"`
	Name string   `json:"name,omitempty"` // Example: X-API-Key.

	// oauth2 properties.
	Flow             oauthFlow         `json:"flow,omitempty"`
	AuthorizationURL string            `json:"authorizationUrl,omitempty"` // Example: https://example.com/oauth/authorize.
	TokenURL         string            `json:"tokenUrl,omitempty"`         // Example: https://example.com/oauth/token.
	Scopes           map[string]string `json:"scopes,omitempty"`           // Example: {"read": "Grants read access", "write": "Grants write access"}.

	// BearerFormat holds arbitrary value for documentation , for example "JWT".
	BearerFormat string `json:"-"`

	Description string `json:"description,omitempty"`
}

SecurityDef holds security definition.

type SwaggerData

type SwaggerData struct {
	CommonFields
	ParamObj
	SchemaObj // nolint:govet
}

SwaggerData holds parameter and schema information for swagger definition.

func (SwaggerData) IgnoreTypeName added in v0.6.23

func (s SwaggerData) IgnoreTypeName()

IgnoreTypeName is a marker interface for github.com/swaggest/jsonschema-go.

func (SwaggerData) Param

func (s SwaggerData) Param() ParamObj

Param returns parameter object.

func (SwaggerData) Schema

func (s SwaggerData) Schema() SchemaObj

Schema returns schema object.

func (SwaggerData) SwaggerDef

func (s SwaggerData) SwaggerDef() SwaggerData

SwaggerDef returns schema object.

type WithStatusCode

type WithStatusCode interface {
	StatusCode() int
}

WithStatusCode is an interface to expose http status code.

Directories

Path Synopsis
internal
Fancy-Path
Package fancypath is a test package.
Package fancypath is a test package.
sample
Package sample is a test package.
Package sample is a test package.
sample/experiment
Package experiment is a test package.
Package experiment is a test package.
sample/experiment/variation
Package variation is a test package.
Package variation is a test package.
Package refl provides reflection helpers.
Package refl provides reflection helpers.
Package swjschema provides adapter for github.com/swaggest/jsonschema-go.
Package swjschema provides adapter for github.com/swaggest/jsonschema-go.

Jump to

Keyboard shortcuts

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