model

package
v0.0.0-...-20d481a Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2018 License: Apache-2.0 Imports: 19 Imported by: 1

Documentation

Index

Examples

Constants

View Source
const (
	TypeNull    = "null"
	TypeBoolean = "boolean"
	TypeInteger = "integer"
	TypeNumber  = "number"
	TypeString  = "string"
	TypeObject  = "object"
	TypeArray   = "array"
	TypeFile    = "file"
	TypeBinary  = "binary"
)

RAML built-in types

Variables

View Source
var (
	ErrorCacheNotFound                    = errutil.NewFactory("cache not found")
	ErrorLoadExternalLibrary1             = errutil.NewFactory("load external library failed: %q")
	ErrorUnsupportedParserConfig1         = errutil.NewFactory("unsupported parser config: %q")
	ErrorUnsupportedValueType1            = errutil.NewFactory("unsupported value type: %T")
	ErrorUnsupportedIncludeType1          = errutil.NewFactory("unsupported include for type: %q")
	ErrorInvalidParserConfigValueType2    = errutil.NewFactory(`value type should be "%T" but got "%T"`)
	ErrorInvalidParserConfigValueType3    = errutil.NewFactory(`value type of parser config %q should be "%T" but got "%T"`)
	ErrorInvalidTargetLocation1           = errutil.NewFactory("invalid TargetLocation string %q")
	ErrorUnexpectedRAMLVersion2           = errutil.NewFactory("RAML version should be %q but got %q")
	ErrorEmptyRootDocumentMediaType       = errutil.NewFactory("body without MIME-type and root document do not provide default MediaType")
	ErrorAnnotationTypeUndefined1         = errutil.NewFactory("Annotation type %q is not found in RAML")
	ErrorInvalidAnnotationTargetLocation2 = errutil.NewFactory("Annotation %q is invalid for TargetLocation %q")
	ErrorTypeUndefined1                   = errutil.NewFactory("Type %q is not found in RAML")
	ErrorTypeConvertFailed2               = errutil.NewFactory("can not convert type from %q to %q")
	ErrorTypo2                            = errutil.NewFactory("detect typo error on %q: %v")
	ErrorArrayElementTypeMismatch3        = errutil.NewFactory("array element %d type mismatch, expected %q but got %q")
	ErrorPropertyTypeMismatch1            = errutil.NewFactory("Property %q type mismatch")
	ErrorPropertyTypeMismatch2            = errutil.NewFactory("Property type mismatch, expected %q but got %q")
	ErrorPropertyTypeMismatch3            = errutil.NewFactory("Property %q type mismatch, expected %q but got %q")
	ErrorPropertyUndefined2               = errutil.NewFactory("Property %q is not found in APIType %q")
	ErrorRequiredProperty2                = errutil.NewFactory("Property %q is required but not found in %q")
	ErrorUnusedTrait1                     = errutil.NewFactory("Trait %q is unused")
	ErrorUnusedAnnotation1                = errutil.NewFactory("Annotation %q is unused")
	ErrorTraitNotFound1                   = errutil.NewFactory("trait %q not found")
	ErrorUseNotFound1                     = errutil.NewFactory("use %q not found")
	ErrorYAMLParseFailed                  = errutil.NewFactory("YAML parse failed")
	ErrorYAMLParseFailed1                 = errutil.NewFactory("%v\nYAML parse failed")
)

errors

Functions

func CheckValueAPIType

func CheckValueAPIType(apiType APIType, value Value, options ...CheckValueOption) (err error)

CheckValueAPIType check value is valid for apiType

func GetLinesInRange

func GetLinesInRange(data string, sep string, line int64, distance int64) string

GetLinesInRange return text from (line - distance) to (line + distance)

Example
data := strings.TrimSpace(`
#%RAML 1.0
types:
    User:
        type: object
        properties:
            name:  string
            email: string
        examples:
            user1:
                name:  Alice
                email: alice@example.com
            user2:
                name:  Bob
                email: bob@example.com
	`)
fmt.Printf("line 5, distance 1\n%s\n", GetLinesInRange(data, "\n", 5, 1))
Output:

line 5, distance 1
        type: object
        properties:
            name:  string

func IsArrayType

func IsArrayType(name string) (originName string, isArray bool)

IsArrayType check name has suffix []

func LoadRAMLFromDir

func LoadRAMLFromDir(dirPath string) (ramlData []byte, err error)

LoadRAMLFromDir load RAML data from directory, concat *.raml

func ParseYAMLError

func ParseYAMLError(yamlErr error) (line int64, reason string, ok bool)

ParseYAMLError return the error detail info if it's an YAML parse error, yaml parser return error without export error type, so using regexp to check

Example
err := errors.New("yaml: line 596: did not find expected key")
line, reason, ok := ParseYAMLError(err)
fmt.Printf("line: %d\nreason: %q\nok: %v\n", line, reason, ok)
Output:

line: 596
reason: "did not find expected key"
ok: true

Types

type APIType

type APIType struct {
	TypeDeclaration
	ObjectType
	ScalarType
	String
	ArrayType
	FileType

	// Type without [] suffix
	BaseType string `yaml:"-" json:"-"`
	// used when custom type, NativeType store the type that should be checked
	NativeType string `yaml:"-" json:"-"`
	// IsArray means the NativeType is array or not
	IsArray bool `yaml:"-" json:"-"`
}

APIType wrap types defined in spec

func NewAPIType

func NewAPIType() *APIType

NewAPIType return empty APIType

func (APIType) IsEmpty

func (t APIType) IsEmpty() bool

IsEmpty return true if it is empty

func (*APIType) UnmarshalYAML

func (t *APIType) UnmarshalYAML(unmarshaler func(interface{}) error) (err error)

UnmarshalYAML implement yaml unmarshaler

type APITypes

type APITypes struct {
	MapAPITypes

	Value Value
	// contains filtered or unexported fields
}

APITypes wraps map of APIType for unmarshal YAML

func (APITypes) IsEmpty

func (t APITypes) IsEmpty() bool

IsEmpty return true if it is empty

func (*APITypes) UnmarshalYAMLTag

func (t *APITypes) UnmarshalYAMLTag(unmarshaler func(interface{}) error, tag string) (err error)

UnmarshalYAMLTag unmarshal an ApiTypes which MIGHT be a simple string or a map[string]*APIType{}

type Annotation

type Annotation struct {
	Value

	// fill by fixAnnotationBracket
	Name string `yaml:"-"`
	// fill by fillAnnotation
	AnnotationType AnnotationType `yaml:"-"`
}

Annotation wrap types defined in spec

type AnnotationType

type AnnotationType struct {
	APIType

	// The locations to which annotations are restricted. If this node
	// is specified, annotations of this type may be applied only on
	// a node corresponding to one of the locations.
	// The value MUST be one or more of the options described in the
	// Target Locations.
	AllowedTargets TargetLocations `yaml:"allowedTargets" json:"allowedTargets,omitempty"`
}

AnnotationType wrap types defined in spec

func (AnnotationType) IsEmpty

func (t AnnotationType) IsEmpty() bool

IsEmpty return true if it is empty

func (*AnnotationType) UnmarshalYAML

func (t *AnnotationType) UnmarshalYAML(unmarshaler func(interface{}) error) (err error)

UnmarshalYAML implement yaml unmarshaler

type AnnotationTypes

type AnnotationTypes map[string]*AnnotationType

AnnotationTypes map of AnnotationType

func (AnnotationTypes) IsEmpty

func (t AnnotationTypes) IsEmpty() bool

IsEmpty return true if it is empty

type Annotations

type Annotations map[string]*Annotation

Annotations map of Annotation

func (Annotations) IsEmpty

func (t Annotations) IsEmpty() bool

IsEmpty return true if it is empty

type ArrayType

type ArrayType struct {
	// Boolean value that indicates if items in the array MUST be unique.
	UniqueItems bool `yaml:"uniqueItems" json:"uniqueItems,omitempty"`

	// Indicates the type all items in the array are inherited from.
	// Can be a reference to an existing type or an inline type declaration.
	Items Unimplement `yaml:"items" json:"items,omitempty"`

	// Minimum amount of items in array. Value MUST be equal to or greater than 0.
	// Default: 0.
	MinItems int64 `yaml:"minItems" json:"minItems,omitempty"`

	// Maximum amount of items in array. Value MUST be equal to or greater than 0.
	// Default: 2147483647.
	MaxItems int64 `yaml:"maxItems" json:"maxItems,omitdefault" default:"2147483647"`
}

ArrayType Array types are declared by using either the array qualifier [] at the end of a type expression or array as the value of a type facet. If you are defining a top-level array type, such as the Emails in the examples below, you can declare the following facets in addition to those previously described to further restrict the behavior of the array type.

func (*ArrayType) BeforeUnmarshalYAML

func (t *ArrayType) BeforeUnmarshalYAML() (err error)

BeforeUnmarshalYAML implement yaml Initiator

func (*ArrayType) IsEmpty

func (t *ArrayType) IsEmpty() bool

IsEmpty return true if it is empty

type Bodies

type Bodies map[string]*Body

Bodies map of Body

func (Bodies) IsEmpty

func (t Bodies) IsEmpty() bool

IsEmpty return true if it is empty

func (*Bodies) UnmarshalYAML

func (t *Bodies) UnmarshalYAML(unmarshaler func(interface{}) error) (err error)

UnmarshalYAML unmarshal from YAML

type Body

type Body struct {
	APIType
}

Body used for Bodies. Some method verbs expect the resource to be sent as a request body. For example, to create a resource, the request must include the details of the resource to create. Resources CAN have alternate representations. For example, an API might support both JSON and XML representations.

type CheckValueOption

type CheckValueOption interface{}

CheckValueOption for changing CheckValueAPIType behavior

type CheckValueOptionAllowArrayToBeNull

type CheckValueOptionAllowArrayToBeNull bool

CheckValueOptionAllowArrayToBeNull allow array type to be null, default: false

type CheckValueOptionAllowIntegerToBeNumber

type CheckValueOptionAllowIntegerToBeNumber bool

CheckValueOptionAllowIntegerToBeNumber allow type integer to be type number, e.g. APIType need a integer, but value is a number default: false

type CheckValueOptionAllowRequiredPropertyToBeEmpty

type CheckValueOptionAllowRequiredPropertyToBeEmpty bool

CheckValueOptionAllowRequiredPropertyToBeEmpty allow required property to be empty value, but still should be existed only check the following types: TypeString, TypeArray, TypeObject, TypeBinary default: false

type Example

type Example struct {
	SingleExample
	// contains filtered or unexported fields
}

Example wrap SingleExample for unmarshal YAML

func (*Example) UnmarshalYAMLTag

func (t *Example) UnmarshalYAMLTag(unmarshaler func(interface{}) error, tag string) (err error)

UnmarshalYAMLTag unmarshal an Example which MIGHT be a simple string or a map[string]interface{}

type Examples

type Examples map[string]*Example

Examples The OPTIONAL examples facet can be used to attach multiple examples to a type declaration. Its value is a map of key-value pairs, where each key represents a unique identifier for an example and the value is a single example.

func (Examples) IsEmpty

func (t Examples) IsEmpty() bool

IsEmpty return true if it is empty

type FileType

type FileType struct {
	// A list of valid content-type strings for the file.
	// The file type */* MUST be a valid value.
	FileTypes []string `yaml:"fileTypes" json:"fileTypes,omitempty"`

	// Specifies the minimum number of bytes for a parameter value.
	// The value MUST be equal to or greater than 0.
	// Default: 0
	MinLength int64 `yaml:"minLength" json:"minLength,omitempty"`

	// Specifies the maximum number of bytes for a parameter value.
	// The value MUST be equal to or greater than 0.
	// Default: 2147483647
	MaxLength int64 `yaml:"maxLength" json:"maxLength,omitdefault" default:"2147483647"`
}

FileType The ​file​ type can constrain the content to send through forms. When this type is used in the context of web forms it SHOULD be represented as a valid file upload in JSON format. File content SHOULD be a base64-encoded string.

func (*FileType) BeforeUnmarshalYAML

func (t *FileType) BeforeUnmarshalYAML() (err error)

BeforeUnmarshalYAML implement yaml Initiator

func (*FileType) IsEmpty

func (t *FileType) IsEmpty() bool

IsEmpty return true if it is empty

type HTTPCode

type HTTPCode int // e.g. 200

HTTPCode For extra clarity

func (HTTPCode) String

func (t HTTPCode) String() string
type Header struct {
	Property
}

Header An API's methods can support or require various HTTP headers. The OPTIONAL headers node is used to explicitly specify those headers. The value of the headers node is a map, specifically a properties declaration, as is the value of the properties object of a type declaration. Each property in this declaration object is a header declaration. Each property name specifies an allowed header name. Each property value specifies the header value type as a type name or an inline type declaration.

type Headers

type Headers struct {
	Properties
}

Headers map of Header

type IsTraits

type IsTraits []*Trait

IsTraits slice of Trait

func (IsTraits) IsEmpty

func (t IsTraits) IsEmpty() bool

IsEmpty return true if it is empty

type Libraries

type Libraries map[string]*Library

Libraries map of Library

func (Libraries) IsEmpty

func (t Libraries) IsEmpty() bool

IsEmpty return true if it is empty

type Library

type Library struct {
	Name string `json:",omitempty"`

	LibraryRAML
}

var _ loadExternalUse = Libraries{}

func (t Libraries) loadExternalUse(conf PostProcessConfig) (err error) {
	for name, library := range t {
		filePath := filepath.Join(conf.RootDocument().WorkingDirectory, library.Name)

		fileData, err := ioutil.ReadFile(filePath)
		if err != nil {
			return ErrorLoadExternalLibrary1.New(err, filePath)
		}

		if err = yaml.Unmarshal(fileData, library); err != nil {
			return ErrorLoadExternalLibrary1.New(err, filePath)
		}

		library.Name = name
	}
	return
}

Library wrap LibraryRAML because LibraryRAML may be a string for external library file

func (Library) GetTrait

func (t Library) GetTrait(name string) (result Trait, err error)

GetTrait return trait if found

func (Library) IsEmpty

func (t Library) IsEmpty() bool

IsEmpty return true if it is empty

func (Library) Prefix

func (t Library) Prefix() string

Prefix return "" if Library is not external used

func (*Library) UnmarshalYAML

func (t *Library) UnmarshalYAML(unmarshaler func(interface{}) error) (err error)

UnmarshalYAML unmarshal Library from YAML

type LibraryRAML

type LibraryRAML struct {
	// Describes the content or purpose of a specific library. The value is
	// a string and MAY be formatted using markdown.
	Usage string `yaml:"usage" json:"usage,omitempty"`

	// An alias for the equivalent "types" node for compatibility with
	// RAML 0.8. Deprecated - API definitions should use the "types" node
	// because a future RAML version might remove the "schemas" alias with
	// that node. The "types" node supports XML and JSON schemas.
	Schemas Unimplement `yaml:"schemas" json:"schemas,omitempty"`

	// Declarations of (data) types for use within the API.
	Types APITypes `yaml:"types" json:"types,omitempty"`

	// Declarations of traits for use within the API.
	Traits Traits `yaml:"traits" json:"traits,omitempty"`

	// Declarations of resource types for use within the API.
	ResourceTypes Unimplement `yaml:"resourceTypes" json:"resourceTypes,omitempty"`

	// Declarations of annotation types for use by annotations.
	AnnotationTypes AnnotationTypes `yaml:"annotationTypes" json:"annotationTypes,omitempty"`

	// Annotations to be applied to this API. An annotation is a map having
	// a key that begins with "(" and ends with ")" where the text enclosed
	// in parentheses is the annotation name, and the value is an instance of
	// that annotation.
	Annotations Annotations `yaml:",regexp:\\(.*\\)" json:"annotations,omitempty"`

	// Declarations of security schemes for use within the API.
	SecuritySchemes Unimplement `yaml:"securitySchemes" json:"securitySchemes,omitempty"`

	// Imported external libraries for use within the API.
	Uses Libraries `yaml:"uses" json:"uses,omitempty"`
}

LibraryRAML RAML libraries are used to combine any collection of data type declarations, resource type declarations, trait declarations, and security scheme declarations into modular, externalized, reusable groups. While libraries are intended to define common declarations in external documents, which are then included where needed, libraries can also be defined inline.

func (LibraryRAML) IsEmpty

func (t LibraryRAML) IsEmpty() bool

IsEmpty return true if it is empty

type MapAPITypes

type MapAPITypes map[string]*APIType

func (MapAPITypes) IsEmpty

func (t MapAPITypes) IsEmpty() bool

IsEmpty return true if Example is empty

type Method

type Method struct {
	// An alternate, human-friendly method name in the context of the resource.
	// If the displayName node is not defined for a method, documentation tools
	// SHOULD refer to the resource by its key, which acts as the method name.
	DisplayName string `yaml:"displayName" json:"displayName,omitempty"`

	// A longer, human-friendly description of the method in the context of the
	// resource. Its value is a string and MAY be formatted using markdown.
	Description string `yaml:"description" json:"description,omitempty"`

	// Annotations to be applied to this API. An annotation is a map having
	// a key that begins with "(" and ends with ")" where the text enclosed in
	// parentheses is the annotation name, and the value is an instance of
	// that annotation.
	Annotations Annotations `yaml:",regexp:\\(.*\\)" json:"annotations,omitempty"`

	// Detailed information about any query parameters needed by this method.
	// Mutually exclusive with queryString.
	QueryParameters QueryParameters `yaml:"queryParameters" json:"queryParameters,omitempty"`

	// Detailed information about any request headers needed by this method.
	Headers Headers `yaml:"headers" json:"headers,omitempty"`

	// The query string needed by this method. Mutually exclusive with queryParameters.
	QueryString Unimplement `yaml:"queryString" json:"queryString,omitempty"`

	// Information about the expected responses to a request.
	Responses Responses `yaml:"responses" json:"responses,omitempty"`

	// A request body that the method admits.
	Bodies Bodies `yaml:"body" json:"body,omitempty"`

	// Explicitly specify the protocol(s) used to invoke a method, thereby
	// overriding the protocols set elsewhere, for example in the baseUri
	// or the root-level protocols node.
	Protocols Unimplement `yaml:"protocols" json:"protocols,omitempty"`

	// A list of the traits to apply to this method.
	Is IsTraits `yaml:"is" json:"is,omitempty"`

	// The security schemes that apply to this method.
	SecuredBy Unimplement `yaml:"securedBy" json:"securedBy,omitempty"`

	// The field used for check typo error in RAML file
	TypoCheck typoCheck `yaml:",regexp:.*" json:"-"`
}

Method RESTful API methods are operations that are performed on a resource. The OPTIONAL properties get, patch, put, post, delete, head, and options of a resource define its methods; these correspond to the HTTP methods defined in the HTTP version 1.1 specification RFC2616 and its extension, RFC5789. The value of these method properties is a map that has the following key-value pairs:

func (Method) IsEmpty

func (t Method) IsEmpty() bool

IsEmpty return true if it is empty

type Methods

type Methods map[string]*Method

Methods map of Method

func (Methods) IsEmpty

func (t Methods) IsEmpty() bool

IsEmpty return true if it is empty

type ObjectType

type ObjectType struct {
	// The properties that instances of this type can or must have.
	Properties Properties `yaml:"properties" json:"properties,omitempty"`

	// The minimum number of properties allowed for instances of this type.
	MinProperties Unimplement `yaml:"minProperties" json:"minProperties,omitempty"`

	// The maximum number of properties allowed for instances of this type.
	MaxProperties Unimplement `yaml:"maxProperties" json:"maxProperties,omitempty"`

	// A Boolean that indicates if an object instance has additional properties.
	// Default: true
	AdditionalProperties bool `yaml:"additionalProperties" json:"additionalProperties,omitdefault" default:"true"`

	// Determines the concrete type of an individual object at runtime when,
	// for example, payloads contain ambiguous types due to unions or
	// inheritance. The value must match the name of one of the declared
	// properties of a type. Unsupported practices are inline type declarations
	// and using discriminator with non-scalar properties.
	Discriminator Unimplement `yaml:"discriminator" json:"discriminator,omitempty"`

	// Identifies the declaring type. Requires including a discriminator facet
	// in the type declaration. A valid value is an actual value that might
	// identify the type of an individual object and is unique in the
	// hierarchy of the type. Inline type declarations are not supported.
	// Default: The name of the type
	DiscriminatorValue Unimplement `yaml:"discriminatorValue" json:"discriminatorValue,omitempty"`
}

ObjectType All types that have the built-in object type at the root of their inheritance tree can use the following facets in their type declarations:

func (*ObjectType) BeforeUnmarshalYAML

func (t *ObjectType) BeforeUnmarshalYAML() (err error)

BeforeUnmarshalYAML implement yaml Initiator

func (ObjectType) IsEmpty

func (t ObjectType) IsEmpty() bool

IsEmpty return true if it is empty

type Parser

type Parser interface {
	// Config Parser to change the behavior of parsing
	Config(config parserConfig.Enum, value interface{}) (err error)

	// Get Parser Config
	Get(config parserConfig.Enum) (value interface{}, err error)

	// ParseFile Parse a RAML file.
	// Return RootDocument or an error if something went wrong.
	ParseFile(filePath string) (rootdoc RootDocument, err error)

	// ParseFile Parse RAML from bynary data.
	// Return RootDocument or an error if something went wrong.
	ParseData(data []byte, workdir string) (rootdoc RootDocument, err error)
}

Parser used to parse raml file

Example
package main

import (
	"fmt"
	"strings"

	parser "github.com/mattbaird/RAMbLOn/ramlv1.0"
	parserConfig "github.com/mattbaird/RAMbLOn/ramlv1.0/parserConfig"
)

func main() {
	ramlParser := parser.NewParser()
	chkopts := []parser.CheckValueOption{
		parser.CheckValueOptionAllowArrayToBeNull(true),
		parser.CheckValueOptionAllowIntegerToBeNumber(true),
	}
	if err := ramlParser.Config(parserConfig.CheckValueOptions, chkopts); err != nil {
		fmt.Println(err)
	}
	data := []byte(strings.TrimSpace(`
#%RAML 1.0
types:
    User:
        type: object
        properties:
            name: string
        examples:
            example1:
                name: Alice
            example2:
                name: Bob
/user:
    get:
        responses:
            200:
                body:
                    application/json:
                        type: User[]
	`))
	workdir := "."

	rootdoc, err := ramlParser.ParseData(data, workdir)
	if err != nil {
		fmt.Println(err)
	}

	if userType := rootdoc.Types["User"]; userType != nil {
		fmt.Println("User type:", userType.Type)
		for _, property := range userType.Properties.Slice() {
			fmt.Println("Property:", property.Name)
		}
	}

}
Output:

User type: object
Property: name
Example (Cache)
package main

import (
	"fmt"
	"os"

	parser "github.com/mattbaird/RAMbLOn/ramlv1.0"
	parserConfig "github.com/mattbaird/RAMbLOn/ramlv1.0/parserConfig"
)

func main() {
	cacheDirectory := ".cache"
	ramlFilePath := "./raml-examples/others/mobile-order-api/api.raml"

	if err := os.RemoveAll(cacheDirectory); err != nil {
		fmt.Println(err)
	}

	ramlParser := parser.NewParser()
	if err := ramlParser.Config(parserConfig.CacheDirectory, cacheDirectory); err != nil {
		fmt.Println(err)
	}

	rootdoc, err := ramlParser.ParseFile(ramlFilePath)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(rootdoc.Title)

	if _, err := os.Stat(cacheDirectory); os.IsNotExist(err) {
		fmt.Println("cache directory should exist")
	}

	rootdoc, err = ramlParser.ParseFile(ramlFilePath)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(rootdoc.Title)

	if err := os.RemoveAll(cacheDirectory); err != nil {
		fmt.Println(err)
	}

	if _, err := os.Stat(cacheDirectory); err == nil {
		fmt.Println("cache directory should not exist")
	}

}
Output:

Mobile Order API
Mobile Order API

func NewParser

func NewParser() Parser

NewParser create Parser instance

type Properties

type Properties struct {
	Mapdata map[string]*Property
	// contains filtered or unexported fields
}

Properties contain multiple Property

func (Properties) IsEmpty

func (t Properties) IsEmpty() bool

IsEmpty return true if it is empty

func (Properties) Map

func (t Properties) Map() map[string]*Property

Map return properties map

func (Properties) MarshalBinary

func (t Properties) MarshalBinary() ([]byte, error)

MarshalBinary marshal to binary

func (Properties) MarshalJSON

func (t Properties) MarshalJSON() ([]byte, error)

MarshalJSON marshal to json

func (Properties) Slice

func (t Properties) Slice() []*Property

Slice return properties slice

func (*Properties) UnmarshalBinary

func (t *Properties) UnmarshalBinary(data []byte) (err error)

UnmarshalBinary unmarshal from binary

func (*Properties) UnmarshalYAML

func (t *Properties) UnmarshalYAML(unmarshaler func(interface{}) error) (err error)

UnmarshalYAML implement yaml unmarshaler

type Property

type Property struct {
	APIType
	PropertyExtra
}

Property of a object type

func (*Property) IsEmpty

func (t *Property) IsEmpty() bool

IsEmpty return true if it is empty

func (*Property) UnmarshalYAML

func (t *Property) UnmarshalYAML(unmarshaler func(interface{}) error) (err error)

UnmarshalYAML implement yaml unmarshaler a Property which MIGHT be a simple string or a map[string]interface{}

type PropertyExtra

type PropertyExtra struct {
	// Specifies that the property is required or not.
	// Default: true.
	Required bool `yaml:"required" json:"required,omitdefault" default:"true"`

	// Property Name, filled by Properties.UnmarshalYAML()
	Name string `yaml:"-" json:"name,omitempty"`
}

PropertyExtra contain fields no in APIType

func (*PropertyExtra) BeforeUnmarshalYAML

func (t *PropertyExtra) BeforeUnmarshalYAML() (err error)

BeforeUnmarshalYAML implement yaml Initiator

func (*PropertyExtra) IsEmpty

func (t *PropertyExtra) IsEmpty() bool

IsEmpty return true if it is empty

type QueryParameter

type QueryParameter struct {
	Property
}

QueryParameter The queryParameters node specifies the set of query parameters from which the query string is composed. When applying the restrictions defined by the API, processors MUST regard the query string as a set of query parameters according to the URL encoding format. The value of the queryParameters node is a properties declaration object, as is the value of the properties object of a type declaration. Each property in this declaration object is referred to as a query parameter declaration. Each property name specifies an allowed query parameter name. Each property value specifies the query parameter value type as the name of a type or an inline type declaration.

type QueryParameters

type QueryParameters struct {
	Properties
}

QueryParameters map of QueryParameter

type Resource

type Resource struct {
	// An alternate, human-friendly name for the resource. If the displayName
	// node is not defined for a resource, documentation tools SHOULD refer to
	// the resource by its key, which acts as the resource name. For example,
	// tools should refer to the relative URI /jobs.
	DisplayName string `yaml:"displayName" json:"displayName,omitempty"`

	// A substantial, human-friendly description of a resource. Its value is a
	// string and MAY be formatted using markdown.
	Description string `yaml:"description" json:"description,omitempty"`

	// Annotations to be applied to this API. An annotation is a map having
	// a key that begins with "(" and ends with ")" where the text enclosed in
	// parentheses is the annotation name, and the value is an instance of that
	// annotation.
	Annotations Annotations `yaml:",regexp:\\(.*\\)" json:"annotations,omitempty"`

	// The object describing the method.
	Methods Methods `yaml:",regexp:(get|patch|put|post|delete|options|head)" json:"methods,omitempty"`

	// A list of traits to apply to all methods declared (implicitly or
	// explicitly) for this resource. Individual methods can override this
	// declaration.
	Is IsTraits `yaml:"is" json:"is,omitempty"`

	// The resource type that this resource inherits.
	Type APIType `yaml:"type" json:"type,omitempty"`

	// The security schemes that apply to all methods declared (implicitly or
	// explicitly) for this resource.
	SecuredBy Unimplement `yaml:"securedBy" json:"securedBy,omitempty"`

	// Detailed information about any URI parameters of this resource.
	URIParameters APITypes `yaml:"uriParameters" json:"uriParameters,omitempty"`

	// A nested resource, which is identified as any node whose name begins
	// with a slash ("/"), and is therefore treated as a relative URI.
	Resources Resources `yaml:",regexp:/.*" json:"resources,omitempty"`
}

Resource is identified by its relative URI, which MUST begin with a slash ("/"). Every node whose key begins with a slash, and is either at the root of the API definition or is the child node of a resource node, is such a resource node.

func (Resource) IsEmpty

func (t Resource) IsEmpty() bool

IsEmpty return true if it is empty

type Resources

type Resources map[string]*Resource

Resources map of Resource

func (Resources) FillURIParams

func (t Resources) FillURIParams() (err error)

func (Resources) IsEmpty

func (t Resources) IsEmpty() bool

IsEmpty return true if it is empty

type Response

type Response struct {
	// A substantial, human-friendly description of a response. Its value is
	// a string and MAY be formatted using markdown.
	Description string `yaml:"description" json:"description,omitempty"`

	// Annotations to be applied to this API. An annotation is a map having
	// a key that begins with "(" and ends with ")" where the text enclosed
	// in parentheses is the annotation name, and the value is an instance of
	// that annotation.
	Annotations Annotations `yaml:",regexp:\\(.*\\)" json:"annotations,omitempty"`

	// Detailed information about any response headers returned by this method
	Headers Headers `yaml:"headers" json:"headers,omitempty"`

	// The body of the response
	Bodies Bodies `yaml:"body" json:"body,omitempty"`
}

Response The value of a response declaration is a map that can contain any of the following key-value pairs:

func (Response) IsEmpty

func (t Response) IsEmpty() bool

IsEmpty return true if it is empty

type Responses

type Responses map[HTTPCode]*Response

Responses map of Response

func (Responses) IsEmpty

func (t Responses) IsEmpty() bool

IsEmpty return true if it is empty

func (Responses) MarshalJSON

func (t Responses) MarshalJSON() ([]byte, error)

MarshalJSON marshal to json

type RootDocument

type RootDocument struct {
	Library
	RootDocumentExtra

	// directory of RAML file
	WorkingDirectory string `json:",omitempty"`
}

RootDocument The root section of the RAML document describes the basic information about an API, such as its title and version. The root section also defines assets used elsewhere in the RAML document, such as types and traits.

func (RootDocument) IsEmpty

func (t RootDocument) IsEmpty() bool

IsEmpty return true if it is empty

func (*RootDocument) UnmarshalYAML

func (t *RootDocument) UnmarshalYAML(unmarshaler func(interface{}) error) (err error)

UnmarshalYAML unmarshal RootDocument from YAML

type RootDocumentExtra

type RootDocumentExtra struct {
	// A short, plain-text label for the API. Its value is a string.
	Title string `yaml:"title" json:"title,omitempty"`

	// A substantial, human-friendly description of the API. Its value is a
	// string and MAY be formatted using markdown.
	Description string `yaml:"description" json:"description,omitempty"`

	// The version of the API, for example "v1". Its value is a string.
	Version string `yaml:"version" json:"version,omitempty"`

	// A URI that serves as the base for URIs of all resources. Often used as
	// the base of the URL of each resource containing the location of the API.
	// Can be a template URI.
	BaseURI string `yaml:"baseUri" json:"baseUri,omitempty"`

	// Named parameters used in the baseUri (template).
	BaseURIParameters APITypes `yaml:"baseUriParameters" json:"baseUriParameters,omitempty"`

	// The protocols supported by the API.
	Protocols Unimplement `yaml:"protocols" json:"protocols,omitempty"`

	// The default media types to use for request and response bodies
	// (payloads), for example "application/json".
	MediaType string `yaml:"mediaType" json:"mediaType,omitempty"`

	// Additional overall documentation for the API.
	Documentation Unimplement `yaml:"documentation" json:"documentation,omitempty"`

	// The security schemes that apply to every resource and method in the API.
	SecuredBy Unimplement `yaml:"securedBy" json:"securedBy,omitempty"`

	// The resources of the API, identified as relative URIs that begin with
	// a slash (/). A resource node is one that begins with the slash and is
	// either at the root of the API definition or a child of a resource node.
	// For example, /users and /{groupId}.
	Resources Resources `yaml:",regexp:/.*" json:"resources,omitempty"`
}

RootDocumentExtra contain fields no in Library

func (RootDocumentExtra) IsEmpty

func (t RootDocumentExtra) IsEmpty() bool

IsEmpty return true if it is empty

type ScalarType

type ScalarType struct {
	// Enumeration of possible values for this built-in scalar type.
	// The value is an array containing representations of possible values,
	// or a single value if there is only one possible value.
	Enum []Value `yaml:"enum" json:"enum,omitempty"`
}

ScalarType RAML defines a set of built-in scalar types, each of which has a predefined set of restrictions. All types, except the file type, can have an additional enum facet.

func (*ScalarType) IsEmpty

func (t *ScalarType) IsEmpty() bool

IsEmpty return true if it is empty

type SingleExample

type SingleExample struct {
	// An alternate, human-friendly name for the example. If the example is
	// part of an examples node, the default value is the unique identifier
	// that is defined for this example.
	DisplayName string `yaml:"displayName" json:"displayName,omitempty"`

	// A substantial, human-friendly description for an example. Its value is
	// a string and MAY be formatted using markdown.
	Description string `yaml:"description" json:"description,omitempty"`

	// Annotations to be applied to this API. An annotation is a map having a
	// key that begins with "(" and ends with ")" where the text enclosed in
	// parentheses is the annotation name, and the value is an instance of
	// that annotation.
	Annotations Annotations `yaml:",regexp:\\(.*\\)" json:"annotations,omitempty"`

	// The actual example of a type instance.
	Value Value `yaml:"value" json:"value,omitempty"`

	// Validates the example against any type declaration (the default), or not.
	// Set this to false avoid validation.
	Strict bool `yaml:"strict" json:"strict,omitempty"`
}

SingleExample The OPTIONAL example facet can be used to attach an example of a type instance to the type declaration. There are two ways to represent the example facet value: as an explicit description of a specific type instance and as a map that contains additional facets.

func (SingleExample) IsEmpty

func (t SingleExample) IsEmpty() bool

IsEmpty return true if Example is empty

type String

type String struct {
	// Regular expression that this string should match.
	Pattern string `yaml:"pattern" json:"pattern,omitempty"`

	// Minimum length of the string. Value MUST be equal to or greater than 0.
	// Default: 0
	MinLength int64 `yaml:"minLength" json:"minLength,omitempty"`

	// Maximum length of the string. Value MUST be equal to or greater than 0.
	// Default: 2147483647
	MaxLength int64 `yaml:"maxLength" json:"maxLength,omitdefault" default:"2147483647"`
}

String A JSON string with the following additional facets:

func (*String) BeforeUnmarshalYAML

func (t *String) BeforeUnmarshalYAML() (err error)

BeforeUnmarshalYAML implement yaml Initiator

func (*String) IsEmpty

func (t *String) IsEmpty() bool

IsEmpty return true if String is empty

type SupportToCheckEmpty

type SupportToCheckEmpty interface {
	IsEmpty() bool
}

SupportToCheckEmpty implement IsEmpty() instance

type TargetLocation

type TargetLocation int8

TargetLocation the location within an API specification where annotations can be applied MUST be one of the target locations in the following Target Locations table. The targets are the locations themselves, not sub-properties within the locations; for example, the Method target refers to the method node, not to the method display name, description, and so on.

const (
	// The root of a RAML document
	TargetLocationAPI TargetLocation = 1 + iota
	// An item in the collection of items that is the value of the root-level documentation node
	TargetLocationDocumentationItem
	// A resource (relative URI) node, root-level or nested
	TargetLocationResource
	// A method node
	TargetLocationMethod
	// A declaration of the responses node, whose key is an HTTP status code
	TargetLocationResponse
	// The body node of a method
	TargetLocationRequestBody
	// The body node of a response
	TargetLocationResponseBody
	// A data type declaration (inline or in a global types collection),
	// header declaration, query parameter declaration, URI parameter declaration,
	// or a property within any of these declarations, where the type property
	// can be used
	TargetLocationTypeDeclaration
	// Either an example or examples node
	TargetLocationExample
	// A resource type node
	TargetLocationResourceType
	// A trait node
	TargetLocationTrait
	// A security scheme declaration
	TargetLocationSecurityScheme
	// The settings node of a security scheme declaration
	TargetLocationSecuritySchemeSettings
	// A declaration of the annotationTypes node, whose key is a name of an annotation type and whose value describes the annotation
	TargetLocationAnnotationType
	// The root of a library
	TargetLocationLibrary
	// The root of an overlay
	TargetLocationOverlay
	// The root of an extension
	TargetLocationExtension
)

List all valid enum

func ParseTargetLocation

func ParseTargetLocation(s string) TargetLocation

ParseTargetLocation string to enum

func (TargetLocation) MarshalJSON

func (t TargetLocation) MarshalJSON() ([]byte, error)

MarshalJSON return jsonfy []byte of enum

func (TargetLocation) String

func (t TargetLocation) String() string

func (*TargetLocation) UnmarshalJSON

func (t *TargetLocation) UnmarshalJSON(b []byte) (err error)

UnmarshalJSON decode json data to enum

type TargetLocations

type TargetLocations []TargetLocation

TargetLocations slice of TargetLocation

func (TargetLocations) IsAllowed

func (t TargetLocations) IsAllowed(targetLocation TargetLocation) bool

IsAllowed return true if targetLocation is allowed

func (TargetLocations) IsEmpty

func (t TargetLocations) IsEmpty() bool

IsEmpty return true if it is empty

func (*TargetLocations) UnmarshalYAML

func (t *TargetLocations) UnmarshalYAML(unmarshaler func(interface{}) error) (err error)

UnmarshalYAML implement yaml unmarshaler

type Trait

type Trait struct {
	String string `json:",omitempty"`

	TraitRAML
}

Trait wrap TraitRAML because TraitRAML may be a string for using trait

func (Trait) IsEmpty

func (t Trait) IsEmpty() bool

IsEmpty return true if it is empty

func (*Trait) UnmarshalYAML

func (t *Trait) UnmarshalYAML(unmarshaler func(interface{}) error) (err error)

UnmarshalYAML implement yaml unmarshaler a Property which MIGHT be a simple string or a map[string]interface{}

type TraitRAML

type TraitRAML struct {
	Method

	// The OPTIONAL usage node of a resource type or trait provides
	// instructions about how and when the resource type or trait should
	// be used. Documentation generators MUST describe this node in terms
	// of the characteristics of the resource and method, respectively.
	// However, the resources and methods MUST NOT inherit the usage node.
	// Neither resources nor methods allow a node named usage.
	Usage string `yaml:"usage" json:"usage,omitempty"`

	// The full resource URI relative to the baseUri if there is one.
	ResourcePath string `yaml:"resourcePath" json:"resourcePath,omitempty"`

	// The rightmost of the non-URI-parameter-containing path fragments.
	ResourcePathName string `yaml:"resourcePathName" json:"resourcePathName,omitempty"`

	// The name of the method
	MethodName string `yaml:"methodName" json:"methodName,omitempty"`
}

TraitRAML like a method, can provide method-level nodes such as description, headers, query string parameters, and responses. Methods that use one or more traits inherit nodes of those traits. A resource and resource type can also use, and thus inherit from, one or more traits, which then apply to all methods of the resource and resource type. Traits are related to methods through a mixing pattern.

func (TraitRAML) IsEmpty

func (t TraitRAML) IsEmpty() bool

IsEmpty return true if it is empty

type Traits

type Traits map[string]*Trait

Traits map of Trait

func (Traits) IsEmpty

func (t Traits) IsEmpty() bool

IsEmpty return true if it is empty

type TypeDeclaration

type TypeDeclaration struct {
	// A default value for a type. When an API request is completely missing
	// the instance of a type, for example when a query parameter described by
	// a type is entirely missing from the request, then the API must act as
	// if the API client had sent an instance of that type with the instance
	// value being the value in the default facet. Similarly, when the API
	// response is completely missing the instance of a type, the client must
	// act as if the API server had returned an instance of that type with
	// the instance value being the value in the default facet. A special case
	// is made for URI parameters: for these, the client MUST substitute the
	// value in the default facet if no instance of the URI parameter was given.
	Default Unimplement `yaml:"default" json:"default,omitempty"`

	// An alias for the equivalent "type" facet for compatibility with RAML
	// 0.8. Deprecated - API definitions should use the "type" facet because
	// the "schema" alias for that facet name might be removed in a future RAML
	// version. The "type" facet supports XML and JSON schemas.
	Schema Unimplement `yaml:"schema" json:"schema,omitempty"`

	// A base type which the current type extends or just wraps. The value of
	// a type node MUST be either a) the name of a user-defined type or b) the
	// name of a built-in RAML data type (object, array, or one of the scalar
	// types) or c) an inline type declaration.
	Type string `yaml:"type" json:"type,omitempty"`

	// An example of an instance of this type that can be used, for example,
	// by documentation generators to generate sample values for an object of
	// this type. The "example" facet MUST not be available when the "examples"
	// facet is already defined. See section Examples for more information.
	Example Example `yaml:"example" json:"example,omitempty"`

	// Examples of instances of this type. This can be used, for example, by
	// documentation generators to generate sample values for an object of this
	// type. The "examples" facet MUST not be available when the "example"
	// facet is already defined. See section Examples for more information.
	Examples Examples `yaml:"examples" json:"examples,omitempty"`

	// An alternate, human-friendly name for the type
	DisplayName string `yaml:"displayName" json:"displayName,omitempty"`

	// A substantial, human-friendly description of the type. Its value is a
	// string and MAY be formatted using markdown.
	Description string `yaml:"description" json:"description,omitempty"`

	// Annotations to be applied to this API. An annotation is a map having a
	// key that begins with "(" and ends with ")" where the text enclosed in
	// parentheses is the annotation name, and the value is an instance of
	// that annotation.
	Annotations Annotations `yaml:",regexp:\\(.*\\)" json:"annotations,omitempty"`

	// A map of additional, user-defined restrictions that will be inherited
	// and applied by any extending subtype. See section User-defined Facets
	// for more information.
	Facets Unimplement `yaml:"facets" json:"facets,omitempty"`

	// The capability to configure XML serialization of this type instance.
	XML Unimplement `yaml:"xml" json:"xml,omitempty"`
}

TypeDeclaration A type declaration references another type, or wraps or extends another type by adding functional facets (e.g. properties) or non-functional facets (e.g. a description), or is a type expression that uses other types. Here are the facets that all type declarations can have; certain type declarations might have other facets:

func (*TypeDeclaration) IsEmpty

func (t *TypeDeclaration) IsEmpty() bool

IsEmpty return true if it is empty

type Unimplement

type Unimplement struct {
	Value
}

Unimplement For extra clarity

type UriParameter

type UriParameter struct {
	Description string
	Type        string
}

type Value

type Value struct {
	Type    string
	Boolean bool
	Integer int64
	Number  float64
	String  string
	Array   []*Value
	Map     map[string]*Value
	Binary  []byte
}

Value multiple types value

func NewValue

func NewValue(src interface{}) (Value, error)

NewValue cast src to value

func NewValueWithAPIType

func NewValueWithAPIType(apiType APIType, src interface{}) (Value, error)

NewValueWithAPIType return Value from src with apiType check

func (Value) IsEmpty

func (t Value) IsEmpty() bool

IsEmpty return true if it is empty

func (Value) IsZero

func (t Value) IsZero() bool

IsZero return true if Value is empty or contains only type name

func (Value) MarshalJSON

func (t Value) MarshalJSON() ([]byte, error)

MarshalJSON marshal to json

func (*Value) UnmarshalYAML

func (t *Value) UnmarshalYAML(unmarshaler func(interface{}) error) (err error)

UnmarshalYAML unmarshal from YAML

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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