openapi

package module
v0.0.0-...-6149f87 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2022 License: MIT Imports: 10 Imported by: 0

README

openapi实验项目

支持tag:

openapi //默认的tag标签名
openapi_desc //如果描述里面带','则可以用这个tag
openapi_extras //额外的字段,和openapi一样,防止出现','用的

示例

package openapi

import (
	"encoding/json"
	"github.com/Chise1/openapi/models"
	"github.com/iancoleman/orderedmap"
	"github.com/stretchr/testify/require"
	"net"
	"net/url"
	"time"
)

type GrandfatherType struct {
	FamilyName string `json:"family_name" openapi:"required"`
}

type SomeBaseType struct {
	SomeBaseProperty     int `json:"some_base_property"`
	SomeBasePropertyYaml int `yaml:"some_base_property_yaml"`
	// The openapi required tag is nonsensical for private and ignored properties.
	// Their presence here tests that the fields *will not* be required in the output
	// schema, even if they are tagged required.
	somePrivateBaseProperty   string          `openapi:"required"`
	SomeIgnoredBaseProperty   string          `json:"-" openapi:"required"`
	SomeSchemaIgnoredProperty string          `openapi:"-,required"`
	Grandfather               GrandfatherType `json:"grand"`

	SomeUntaggedBaseProperty           bool `openapi:"required"`
	someUnexportedUntaggedBaseProperty bool
}

type MapType map[string]interface{}

type nonExported struct {
	PublicNonExported  int
	privateNonExported int
}

type ProtoEnum int32

func (ProtoEnum) EnumDescriptor() ([]byte, []int) { return []byte(nil), []int{0} }

const (
	Unset ProtoEnum = iota
	Great
)

type TestUser struct {
	SomeBaseType
	nonExported
	MapType

	ID      int                    `json:"id" openapi:"required"`
	Name    string                 `json:"name" openapi:"required,minLen=1,maxLen=20,pattern=.*,desc=this is a property,title=the name,example=joe,example=lucy,default=alex"`
	Friends []int                  `json:"friends,omitempty" openapi_desc:"list of IDs, omitted when empty"`
	Tags    map[string]interface{} `json:"tags,omitempty"`

	TestFlag       bool
	IgnoredCounter int `json:"-"`

	// Tests for RFC draft-wright-json-schema-validation-00, section 7.3
	BirthDate time.Time `json:"birth_date,omitempty"`
	Website   url.URL   `json:"website,omitempty"`
	IPAddress net.IP    `json:"network_address,omitempty"`

	// Tests for RFC draft-wright-json-schema-hyperschema-00, section 4
	Photo  []byte `json:"photo,omitempty" openapi:"required"`
	Photo2 Bytes  `json:"photo2,omitempty" openapi:"required"`

	// Tests for jsonpb enum support
	Feeling ProtoEnum `json:"feeling,omitempty"`
	Age     int       `json:"age" openapi:"gt=18,lt=120"`
	Email   string    `json:"email" openapi:"format=email"`

	// Test for "extras" support
	Baz string `openapi_extras:"foo=bar,hello=world,foo=bar1"`

	// Tests for simple enum Tags
	Color      string  `json:"color" openapi:"enum=red,enum=green,enum=blue"`
	Rank       int     `json:"rank,omitempty" openapi:"enum=1,enum=2,enum=3"`
	Multiplier float64 `json:"mult,omitempty" openapi:"enum=1.0,enum=1.5,enum=2.0"`

	// Tests for enum Tags on slices
	Roles      []string  `json:"roles" openapi:"enum=admin,enum=moderator,enum=user"`
	Priorities []int     `json:"priorities,omitempty" openapi:"enum=-1,enum=0,enum=1,enun=2"`
	Offsets    []float64 `json:"offsets,omitempty" openapi:"enum=1.570796,enum=3.141592,enum=6.283185"`

	// Test for raw JSON
	Raw json.RawMessage `json:"raw"`
}

int支持:lt,lte,gt,gte,multi,default,example,enum,required enum的简单写法是:直接用|进行分割。例如

type E struct{
Offsets    []float64 `json:"offsets,omitempty" openapi:"1.570796|3.141592|6.283185"`
}

简写和enum两种方法都支持

tips

来源:jsonschema

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultRes = models.Response{
	Description: "Successful Response",
	Content: map[string]*models.MediaType{
		"application/json": {
			Schema: &models.Schema{},
		},
	},
}
View Source
var OPENAPI = models.OpenAPI{}
View Source
var Version = "http://json-schema.org/draft-04/schema#"

Version is the JSON SchemaChild version. If extending JSON SchemaChild with custom values use a custom URI. RFC draft-wright-json-schema-00, section 6

Functions

func GetExample

func GetExample(schema *models.Schema, v interface{}) map[string]interface{}

Types

type ContentType

type ContentType string
const (
	//Html     ContentType = "text/html"
	//Text     ContentType = "text/plain"
	//TextXml  ContentType = "text/xml"
	//Gif      ContentType = "image/gif"
	//Jpeg     ContentType = "image/jpeg"
	//Png      ContentType = "image/png"
	//AppXml   ContentType = "application/xml"
	Json ContentType = "application/json"
	//Pdf      ContentType = "application/pdf"
	//Stream   ContentType = "application/octet-stream"
	Form     ContentType = "application/x-www-form-urlencoded"
	FormData ContentType = "multipart/form-data"
)

type Definitions

type Definitions map[string]*models.Schema

Definitions hold schema definitions. http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.26 RFC draft-wright-json-schema-validation-00, section 5.26 body

type IBody

type IBody interface {
	Marshal() ([]byte, error)
}

IBody body返回的数据结构

type IContentType

type IContentType interface {
	GetContentType() ContentType
}

IContentType 返回的结构体在请求或返回参数的类型

type Parameters

type Parameters []*models.Parameter

Parameters 路径参数

type Reflector

type Reflector struct {
	// AllowAdditionalProperties will cause the Reflector to generate a schema
	// with additionalProperties to 'true' for all struct types. This means
	// the presence of additional keys in JSON objects will not cause validation
	// to fail. Note said additional keys will simply be dropped when the
	// validated JSON is unmarshalled.
	AllowAdditionalProperties bool

	// RequiredFromJSONSchemaTags will cause the Reflector to generate a schema
	// that requires any key tagged with `jsonschema:required`, overriding the
	// default of requiring any key *not* tagged with `json:,omitempty`.
	RequiredFromJSONSchemaTags bool

	// YAMLEmbeddedStructs will cause the Reflector to generate a schema that does
	// not inline embedded structs. This should be enabled if the JSON schemas are
	// used with yaml.Marshal/Unmarshal.
	YAMLEmbeddedStructs bool

	// Prefer yaml: tags over json: tags to generate the schema even if json: tags
	// are present
	PreferYAMLSchema bool

	// ExpandedStruct will cause the toplevel definitions of the schema not
	// be referenced itself to a definition.
	//把根打散
	ExpandedStruct bool

	// Do not reference definitions.
	// All types are still registered under the "definitions" top-level object,
	// but instead of $ref fields in containing types, the entire definition
	// of the contained type is inserted.
	// This will cause the entire structure of types to be output in one tree.
	DoNotReference bool

	// Use package paths as well as type names, to avoid conflicts.
	// Without this setting, if two packages contain a type with the same name,
	// and both are present in a schema, they will conflict and overwrite in
	// the definition map and produce bad output.  This is particularly
	// noticeable when using DoNotReference.
	FullyQualifyTypeNames bool

	// IgnoredTypes defines a slice of types that should be ignored in the schema,
	// switching to just allowing additional properties instead.
	IgnoredTypes []interface{}

	// TypeMapper is a function that can be used to map custom Go types to jsonschema types.
	TypeMapper func(reflect.Type) *models.Schema

	// TypeNamer allows customizing of type names
	TypeNamer func(reflect.Type) string

	// AdditionalFields allows adding structfields for a given type
	AdditionalFields func(reflect.Type) []reflect.StructField
}

A Reflector reflects values into a SchemaChild.

func (*Reflector) Reflect

func (n *Reflector) Reflect(v interface{}) *SchemaChild

Reflect reflects to SchemaChild from a value.

func (*Reflector) ReflectFromType

func (n *Reflector) ReflectFromType(t reflect.Type) *SchemaChild

ReflectFromType generates root schema

func (*Reflector) TypeName

func (n *Reflector) TypeName(t reflect.Type) string

type RouteStruct

type RouteStruct interface {
	GetReqPara() interface{}
	GetReqBody() interface{}         //interface可以为IContentType
	GetResBody() map[int]interface{} //interface可以为IContentType
	GetResPara() interface{}
	GetDescription() string
	GetPath() string
	GetMethod() string
}

type RouterHelper

type RouterHelper struct {
	Body       *models.RequestBody //这才是真正应该有的body
	Components Definitions         //Body,包含content forms,files
	Parameters Parameters          //path,query,header,cookie, todo path之后在处理
	Response   map[string]*models.Response
	*models.Schema
	ReqContentType string
}

func NewOpenapiRequest

func NewOpenapiRequest(v RouteStruct) *RouterHelper

func Register2Openapi

func Register2Openapi(n RouteStruct) *RouterHelper

func (*RouterHelper) GetSchema

func (n *RouterHelper) GetSchema() *models.Schema

func (*RouterHelper) GetSchemaStruct

func (n *RouterHelper) GetSchemaStruct(schema *models.Schema) *models.Schema

func (*RouterHelper) WriteRes

func (n *RouterHelper) WriteRes(exceptRes map[int]interface{})

type SchemaChild

type SchemaChild struct {
	*models.Schema             //根schema
	Components     Definitions //Body,包含content forms,files
}

SchemaChild is the root schema. RFC draft-wright-json-schema-00, section 4.5

func Reflect

func Reflect(v interface{}) *SchemaChild

Reflect represents a JSON SchemaChild object type. Reflect reflects to SchemaChild from a value using the default Reflector

func ReflectFromType

func ReflectFromType(t reflect.Type) *SchemaChild

ReflectFromType generates root schema using the default Reflector

func (*SchemaChild) MarshalJSON

func (n *SchemaChild) MarshalJSON() ([]byte, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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