connexions

package module
v0.1.8 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2023 License: MIT Imports: 43 Imported by: 0

README

Connexions

CI Endpoint Badge GoReportCard GoDoc License

Connexions is a library originally inspired by Connexion.
Connexion allows you to set up a REST API with Swagger documentation and OAuth2 authentication with minimal effort.

Connexions takes this one step further by allowing you to define multiple APIs not limited to only Swagger and(or) OpenAPI.
You can define single response for any arbitrary path on the fly.

Goals

  • provide a simple tool to work with API mocks
  • combine multiple APIs into one
  • generate meaningful responses

Features

  • Randomized response contents, allowing you to redefine the response for any path in a locale of your choice
  • Mimic error responses and status codes
  • Configurable latency in responses

Simple start

docker run -it --rm \
  -p 2200:2200 \
  -v connexions:/app/resources/data \
  cubahno/connexions api

Read full documentation at cubahno.github.io/connexions.

License

Copyright (c) 2023-present

Licensed under the MIT License

===================

OpenAPI Specification
OpenAPI 3.0 Style Values
Operation Object
YAML format

Documentation

Index

Constants

View Source
const (
	OpenAPIRouteType = "openapi"
	FixedRouteType   = "fixed"
)
View Source
const (
	// RootServiceName is the name and location in the service directory of the service without a name.
	RootServiceName = ".root"

	// RootOpenAPIName is the name and location of the OpenAPI service without a name.
	RootOpenAPIName = ".openapi"
)
View Source
const (
	TypeArray   = "array"
	TypeBoolean = "boolean"
	TypeInteger = "integer"
	TypeNumber  = "number"
	TypeObject  = "object"
	TypeString  = "string"
)
View Source
const (
	ParameterInPath   = "path"
	ParameterInQuery  = "query"
	ParameterInHeader = "header"
	// ParameterInBody v2 Swagger only
	ParameterInBody = "body"
)
View Source
const (
	NULL = "__null__"
)

NULL is used to force resolve to nil

Variables

View Source
var (
	ErrServiceNotFound                  = errors.New("service not found")
	ErrResourceNotFound                 = errors.New("resource not found")
	ErrResourceMethodNotFound           = errors.New("resource method not found")
	ErrOpenAPISpecIsEmpty               = errors.New("OpenAPI spec is empty")
	ErrInvalidHTTPVerb                  = errors.New("invalid HTTP verb")
	ErrInvalidURLResource               = errors.New("invalid URL resource")
	ErrReservedPrefix                   = errors.New("reserved prefix")
	ErrUnexpectedFormDataType           = errors.New("expected map[string]any for multipart/form-data")
	ErrUnexpectedFormURLEncodedType     = errors.New("expected map[string]any for x-www-form-urlencoded")
	ErrOnlyFixedResourcesAllowedEditing = errors.New("only fixed resources are allowed editing")
	ErrGettingFileFromURL               = errors.New("error getting file from url")
)
View Source
var PlaceholderRegex = regexp.MustCompile(`\{[^\}]*\}`)

Replacers is a list of replacers that are used to replace values in schemas and contents in the specified order.

Functions

func AppendSliceFirstNonEmpty

func AppendSliceFirstNonEmpty[T comparable](data []T, value ...T) []T

AppendSliceFirstNonEmpty appends the first non-empty value to the given slice.

func ApplySchemaConstraints

func ApplySchemaConstraints(openAPISchema any, res any) any

ApplySchemaConstraints applies schema constraints to the value. It converts the input value to match the corresponding OpenAPI type specified in the schema.

func CastToSchemaFormat

func CastToSchemaFormat(ctx *ReplaceContext, value any) any

CastToSchemaFormat casts the value to the schema format if possible. If the schema format is not specified, the value is returned as-is.

func CleanupServiceFileStructure

func CleanupServiceFileStructure(servicePath string) error

CleanupServiceFileStructure removes empty directories from the service directory.

func CollectContexts

func CollectContexts(names []map[string]string, fileCollections map[string]map[string]any,
	initial map[string]any) []map[string]any

CollectContexts collects contexts from the given list of context names, file collections and initial context.

func ComposeFileSavePath

func ComposeFileSavePath(descr *ServiceDescription, paths *Paths) string

ComposeFileSavePath composes a save path for a file.

func ComposeOpenAPISavePath

func ComposeOpenAPISavePath(descr *ServiceDescription, baseDir string) string

ComposeOpenAPISavePath composes a save path for an OpenAPI specification. The resulting filename is always index.<spec extension>.

func ConditionalLoggingMiddleware

func ConditionalLoggingMiddleware(cfg *Config) func(http.Handler) http.Handler

ConditionalLoggingMiddleware is a middleware that conditionally can disable logger. For example, in tests or when fetching static files.

func CopyDirectory

func CopyDirectory(src, dest string) error

CopyDirectory copies a directory recursively.

func CopyFile

func CopyFile(srcPath, destPath string) error

CopyFile copies a file from srcPath to destPath. If the destination directory doesn't exist, it will be created.

func CopyNestedMap added in v0.0.54

func CopyNestedMap(source map[string]map[string]any) map[string]map[string]any

CopyNestedMap returns a copy of the given map with all nested maps copied as well.

func EncodeContent

func EncodeContent(content any, contentType string) ([]byte, error)

EncodeContent encodes content to the given content type. Since it is part of the JSON request, we need to encode different content types to string before sending it.

func ExtractPlaceholders

func ExtractPlaceholders(input string) []string

ExtractPlaceholders extracts all placeholders including curly brackets from a pattern.

func ExtractZip

func ExtractZip(zipReader *zip.Reader, targetDir string, onlyPrefixes []string) error

ExtractZip extracts a zip archive to a target directory. onlyPrefixes is a list of prefixes that are allowed to be extracted.

func FixSchemaTypeTypos

func FixSchemaTypeTypos(typ string) string

FixSchemaTypeTypos fixes common typos in schema types.

func GenerateContentArray

func GenerateContentArray(schema *Schema, valueReplacer ValueReplacer, state *ReplaceState) any

GenerateContentArray generates content from the given schema with type `array`.

func GenerateContentFromSchema

func GenerateContentFromSchema(schema *Schema, valueReplacer ValueReplacer, state *ReplaceState) any

GenerateContentFromSchema generates content from the given schema.

func GenerateContentObject

func GenerateContentObject(schema *Schema, valueReplacer ValueReplacer, state *ReplaceState) any

GenerateContentObject generates content from the given schema with type `object`.

func GenerateQuery

func GenerateQuery(valueReplacer ValueReplacer, params OpenAPIParameters) string

GenerateQuery generates query string from the given parameters.

func GenerateRequestHeaders

func GenerateRequestHeaders(parameters OpenAPIParameters, valueReplacer ValueReplacer) any

GenerateRequestHeaders generates request headers from the given parameters.

func GenerateResponseHeaders

func GenerateResponseHeaders(headers OpenAPIHeaders, valueReplacer ValueReplacer) http.Header

GenerateResponseHeaders generates response headers from the given headers.

func GenerateURLFromSchemaParameters

func GenerateURLFromSchemaParameters(path string, valueResolver ValueReplacer, params OpenAPIParameters) string

GenerateURLFromSchemaParameters generates URL from the given path and parameters.

func GetFakeFuncFactoryWithString

func GetFakeFuncFactoryWithString() map[string]FakeFuncFactoryWithString

GetFakeFuncFactoryWithString returns a map of utility fake functions.

func GetFakes

func GetFakes() map[string]FakeFunc

GetFakes returns a map of fake functions from underlying fake library by gathering all exported methods from the faker.Faker struct into map. The keys are the snake_cased dot-separated method names, which reflect the location of the function: For example: person.first_name will return a fake first name from the Person struct.

func GetFileContentsFromURL added in v0.1.5

func GetFileContentsFromURL(client *http.Client, url string) ([]byte, string, error)

func GetFileHash

func GetFileHash(file io.Reader) string

GetFileHash gets the SHA256 hash of a file.

func GetJSONPayload

func GetJSONPayload[T any](req *http.Request) (*T, error)

GetJSONPayload parses JSON payload from the request body into the given type.

func GetOpenAPITypeFromValue added in v0.1.8

func GetOpenAPITypeFromValue(value any) string

func GetRandomKeyFromMap

func GetRandomKeyFromMap[T any](m map[string]T) string

GetRandomKeyFromMap returns a random key from the given map.

func GetRandomSliceValue

func GetRandomSliceValue[T any](slice []T) T

GetRandomSliceValue returns a random value from the given slice.

func GetSliceMaxRepetitionNumber

func GetSliceMaxRepetitionNumber[T comparable](values []T) int

GetSliceMaxRepetitionNumber returns the maximum number of non-unique values in the given slice.

func GetSortedMapKeys

func GetSortedMapKeys[T any](content map[string]T) []string

GetSortedMapKeys returns the keys of the given map sorted alphabetically.

func GetValueByDottedPath

func GetValueByDottedPath(data map[string]any, path string) any

GetValueByDottedPath returns the value of the given path in the given map. If the path does not exist, nil is returned. e.g. GetValueByDottedPath(map[string]any{"a": map[string]any{"b": 1}}, "a.b") returns 1

func HandleErrorAndLatency

func HandleErrorAndLatency(svcConfig *ServiceConfig, w http.ResponseWriter) bool

HandleErrorAndLatency handles error and latency defined in the service configuration. Returns true if error was handled.

func HasCorrectSchemaValue

func HasCorrectSchemaValue(ctx *ReplaceContext, value any) bool

HasCorrectSchemaValue checks if the value is of the correct type and format.

func IsCorrectlyReplacedType

func IsCorrectlyReplacedType(value any, neededType string) bool

IsCorrectlyReplacedType checks if the given value is of the correct schema type.

func IsEmptyDir

func IsEmptyDir(path string) bool

IsEmptyDir checks if a directory is empty.

func IsInteger

func IsInteger(value any) bool

IsInteger checks if the value is an integer

func IsJsonType

func IsJsonType(content []byte) bool

IsJsonType checks if the content is a valid JSON document.

func IsMap

func IsMap(i any) bool

IsMap checks if the value is a map

func IsMatchSchemaReadWriteToState added in v0.1.4

func IsMatchSchemaReadWriteToState(schema *Schema, state *ReplaceState) bool

IsMatchSchemaReadWriteToState checks if the given schema is read-write match. ReadOnly - A property that is only available in a response. WriteOnly - A property that is only available in a request.

func IsNumber

func IsNumber(value any) bool

IsNumber checks if the value is a number: integer or float

func IsSliceUnique

func IsSliceUnique[T comparable](path []T) bool

IsSliceUnique returns true if all values in the given slice are unique.

func IsValidHTTPVerb

func IsValidHTTPVerb(verb string) bool

IsValidHTTPVerb checks if the given HTTP verb is valid.

func IsValidURLResource

func IsValidURLResource(urlPattern string) bool

IsValidURLResource checks if the given URL resource pattern is valid: placeholders contain only alphanumeric characters, underscores, and hyphens

func IsYamlType

func IsYamlType(content []byte) bool

IsYamlType checks if the content is a valid YAML document.

func MaybeRegexPattern

func MaybeRegexPattern(input string) bool

MaybeRegexPattern checks if the input string contains any special characters. This is a simple good-enough check to see if the context key is a regex pattern.

func MustFileStructure

func MustFileStructure(paths *Paths) error

MustFileStructure creates the necessary directories and files

func NewDocumentFromFileFactory

func NewDocumentFromFileFactory(provider SchemaProvider) func(filePath string) (Document, error)

NewDocumentFromFileFactory returns a function that creates a new Document from a file.

func RemovePointer

func RemovePointer[T bool | float64 | int64 | uint64](value *T) T

RemovePointer removes pointer from the boolean or numeric value

func ReplaceFromContext

func ReplaceFromContext(ctx *ReplaceContext) any

ReplaceFromContext is a replacer that replaces values from the context.

func ReplaceFromSchemaExample

func ReplaceFromSchemaExample(ctx *ReplaceContext) any

ReplaceFromSchemaExample is a replacer that replaces values from the schema example.

func ReplaceFromSchemaFallback

func ReplaceFromSchemaFallback(ctx *ReplaceContext) any

ReplaceFromSchemaFallback is the last resort to get a value from the schema.

func ReplaceFromSchemaFormat

func ReplaceFromSchemaFormat(ctx *ReplaceContext) any

ReplaceFromSchemaFormat is a replacer that replaces values from the schema format.

func ReplaceFromSchemaPrimitive

func ReplaceFromSchemaPrimitive(ctx *ReplaceContext) any

ReplaceFromSchemaPrimitive is a replacer that replaces values from the schema primitive.

func ReplaceInHeaders

func ReplaceInHeaders(ctx *ReplaceContext) any

ReplaceInHeaders is a replacer that replaces values only in headers.

func ReplaceInPath

func ReplaceInPath(ctx *ReplaceContext) any

ReplaceInPath is a replacer that replaces values only in path parameters.

func ReplaceValueWithContext

func ReplaceValueWithContext(path []string, contextData any) interface{}

ReplaceValueWithContext is a replacer that replaces values from the context.

func SaveFile

func SaveFile(filePath string, data []byte) error

SaveFile saves a file to the specified path. If the destination directory doesn't exist, it will be created.

func SetValueByDottedPath

func SetValueByDottedPath(data map[string]any, path string, value any)

SetValueByDottedPath sets the value of the given path in the given map. If the path does not exist, it is created. e.g. SetValueByDottedPath(map[string]any{"a": map[string]any{"b": 1}}, "a.b", 2) sets the value of "a.b" to 2 ! This function modifies the given map.

func SliceContains

func SliceContains[T comparable](slice []T, value T) bool

SliceContains returns true if the given slice contains the given value.

func SliceDeleteAtIndex

func SliceDeleteAtIndex[T any](slice []T, index int) []T

SliceDeleteAtIndex deletes an element from a slice at the given index and preserves the order of the slice.

func SliceUnique

func SliceUnique[T comparable](slice []T) []T

SliceUnique returns a new slice with unique values from the given slice.

func ToFloat64

func ToFloat64(value any) (float64, error)

ToFloat64 converts underlying value to float64 if it can be represented as float64

func ToInt32

func ToInt32(value any) (int32, bool)

ToInt32 converts underlying value to int32 if it can be represented as int32

func ToInt64

func ToInt64(value any) (int64, bool)

ToInt64 converts underlying value to int64 if it can be represented as int64

func ToSnakeCase

func ToSnakeCase(input string) string

ToSnakeCase converts a string to snake_case case

func TransformHTTPCode

func TransformHTTPCode(httpCode string) int

TransformHTTPCode transforms HTTP code from the OpenAPI spec to the real HTTP code.

func ValidateRequest

func ValidateRequest(req *http.Request, body *Schema, contentType string) error

ValidateRequest validates request against a schema.

func ValidateResponse

func ValidateResponse(req *http.Request, res *Response, operation Operationer) error

ValidateResponse validates a response against an operation. Response must contain non-empty headers or it'll fail validation.

func ValidateStringWithPattern

func ValidateStringWithPattern(input string, pattern string) bool

ValidateStringWithPattern checks if the input string matches the given pattern.

Types

type APIResponse

type APIResponse struct {
	*BaseResponse
}

APIResponse is a response type for API responses.

func NewAPIResponse

func NewAPIResponse(w http.ResponseWriter) *APIResponse

NewAPIResponse creates a new APIResponse instance.

func (*APIResponse) Send

func (r *APIResponse) Send(data []byte)

Send sends the data to the client.

func (*APIResponse) WithHeader

func (r *APIResponse) WithHeader(key string, value string) *APIResponse

WithHeader adds a header to the response.

func (*APIResponse) WithStatusCode

func (r *APIResponse) WithStatusCode(code int) *APIResponse

WithStatusCode sets the status code of the response.

type Any

type Any interface {
	string | int | bool | float64 | any
}

Any is a type that can be used to represent any type in generics.

type App

type App struct {
	Router *Router
	Paths  *Paths
	// contains filtered or unexported fields
}

App is the main application struct

func NewApp

func NewApp(config *Config) *App

NewApp creates a new App instance from Config and registers predefined blueprints.

func (*App) AddBluePrint

func (a *App) AddBluePrint(bluePrint RouteRegister) error

AddBluePrint adds a new blueprint to the application.

func (*App) Run

func (a *App) Run()

Run starts the application and the server. Blocks until the server is stopped.

type AppConfig

type AppConfig struct {
	// Port is the port number to listen on.
	Port int `json:"port" yaml:"port" koanf:"port"`

	// HomeURL is the URL for the UI home page.
	HomeURL string `json:"homeUrl" yaml:"homeURL" koanf:"homeUrl"`

	// ServiceURL is the URL for the service and resources endpoints in the UI.
	ServiceURL string `json:"serviceUrl" yaml:"serviceURL" koanf:"serviceUrl"`

	// SettingsURL is the URL for the settings endpoint in the UI.
	SettingsURL string `json:"settingsUrl" yaml:"settingsURL" koanf:"settingsUrl"`

	// ContextURL is the URL for the context endpoint in the UI.
	ContextURL string `json:"contextUrl" yaml:"contextUrl" koanf:"contextUrl"`

	// ContextAreaPrefix sets sub-contexts for replacements in path, header or any other supported place.
	//
	// for example:
	// in-path:
	//   user_id: "fake.ids.int8"
	ContextAreaPrefix string `json:"contextAreaPrefix" yaml:"contextAreaPrefix" koanf:"contextAreaPrefix"`

	// DisableUI is a flag whether to disable the UI.
	DisableUI bool `json:"disableUI" yaml:"disableUI" koanf:"disableUI"`

	// DisableSpec is a flag whether to disable the Swagger UI.
	DisableSwaggerUI bool `json:"disableSwaggerUI" yaml:"disableSwaggerUI" koanf:"disableSwaggerUI"`

	// SchemaProvider is the schema provider to use: kin-openapi or libopenapi.
	SchemaProvider SchemaProvider `json:"schemaProvider" yaml:"schemaProvider" koanf:"schemaProvider"`

	// Paths is the paths to various resource directories.
	Paths *Paths `json:"-" koanf:"-"`

	// CreateFileStructure is a flag whether to create the initial resources file structure:
	// contexts, services, etc.
	// It will also copy sample files from the samples directory into services.
	// Default: true
	CreateFileStructure bool `koanf:"createFileStructure" json:"createFileStructure" yaml:"createFileStructure"`

	Editor *EditorConfig `koanf:"editor" json:"editor" yaml:"editor"`
}

AppConfig is the app configuration.

func NewDefaultAppConfig

func NewDefaultAppConfig(baseDir string) *AppConfig

NewDefaultAppConfig creates a new default app config in case the config file is missing, not found or any other error.

func (*AppConfig) IsValidPrefix

func (a *AppConfig) IsValidPrefix(prefix string) bool

IsValidPrefix returns true if the prefix is not a reserved URL.

type BaseHandler

type BaseHandler struct {
}

BaseHandler is a base handler type to be embedded in other handlers.

func NewBaseHandler added in v0.0.54

func NewBaseHandler() *BaseHandler

func (*BaseHandler) Error added in v0.0.54

func (h *BaseHandler) Error(code int, message string, w http.ResponseWriter)

Error sends an error response.

func (*BaseHandler) JSONResponse

func (h *BaseHandler) JSONResponse(w http.ResponseWriter) *JSONResponse

JSONResponse is a response type for JSON responses.

func (*BaseHandler) Response

func (h *BaseHandler) Response(w http.ResponseWriter) *APIResponse

Response is a response type for API responses.

func (*BaseHandler) Success added in v0.0.54

func (h *BaseHandler) Success(message string, w http.ResponseWriter)

Success sends a Success response.

type BaseResponse

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

BaseResponse is a base response type.

type BoolValue

type BoolValue bool

func (BoolValue) Get

func (b BoolValue) Get() any

type BufferedWriter added in v0.0.54

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

BufferedWriter is a writer that captures the response. Used to capture the template execution result.

func NewBufferedResponseWriter added in v0.0.54

func NewBufferedResponseWriter() *BufferedWriter

NewBufferedResponseWriter creates a new buffered writer.

func (*BufferedWriter) Header added in v0.0.54

func (bw *BufferedWriter) Header() http.Header

Header returns the header.

func (*BufferedWriter) Write added in v0.0.54

func (bw *BufferedWriter) Write(p []byte) (int, error)

Write writes the data to the buffer.

func (*BufferedWriter) WriteHeader added in v0.0.54

func (bw *BufferedWriter) WriteHeader(statusCode int)

WriteHeader writes the status code.

type CacheOperationAdapter

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

CacheOperationAdapter is an adapter that caches the result of the wrapped operation. Implements Operationer interface.

func (*CacheOperationAdapter) GetParameters

func (a *CacheOperationAdapter) GetParameters() OpenAPIParameters

GetParameters returns the parameters for the operation.

func (*CacheOperationAdapter) GetRequestBody

func (a *CacheOperationAdapter) GetRequestBody() (*Schema, string)

GetRequestBody returns the request body for the operation.

func (*CacheOperationAdapter) GetResponse

func (a *CacheOperationAdapter) GetResponse() *OpenAPIResponse

GetResponse returns the response for the operation.

func (*CacheOperationAdapter) ID

func (a *CacheOperationAdapter) ID() string

ID returns the ID of the operation.

func (*CacheOperationAdapter) WithParseConfig

func (a *CacheOperationAdapter) WithParseConfig(parseConfig *ParseConfig) Operationer

WithParseConfig sets the ParseConfig for the operation.

type CacheStorage

type CacheStorage interface {
	Set(key string, value any) error
	Get(key string) (any, bool)
}

CacheStorage is an interface that describes a cache storage.

type Config

type Config struct {
	// App is the app config.
	App *AppConfig `koanf:"app" json:"app" yaml:"app"`

	// Services is a map of service name and the corresponding config.
	// ServiceName is the first part of the path.
	// e.g. /petstore/v1/pets -> petstore
	// in case, there's no service name, the name ".root" will be used.
	Services map[string]*ServiceConfig `koanf:"services" json:"services" yaml:"services"`

	Replacers []Replacer `koanf:"-" json:"-" yaml:"-"`
	// contains filtered or unexported fields
}

func MustConfig

func MustConfig(baseDir string) *Config

MustConfig creates a new config from a YAML file path. In case it file does not exist or has incorrect YAML: - it creates a new default config

Koanf has a file watcher, but its easier to control the changes with a manual reload.

func NewConfigFromContent

func NewConfigFromContent(content []byte) (*Config, error)

NewConfigFromContent creates a new config from a YAML file content.

func NewDefaultConfig

func NewDefaultConfig(baseDir string) *Config

NewDefaultConfig creates a new default config in case the config file is missing, not found or any other error.

func (*Config) EnsureConfigValues

func (c *Config) EnsureConfigValues()

EnsureConfigValues ensures that all config values are set.

func (*Config) GetApp

func (c *Config) GetApp() *AppConfig

func (*Config) GetServiceConfig

func (c *Config) GetServiceConfig(service string) *ServiceConfig

GetServiceConfig returns the config for a service. If the service is not found, it returns a default config.

func (*Config) Reload

func (c *Config) Reload()

type ContentExample

type ContentExample struct {
	CURL string `json:"curl,omitempty"`
}

ContentExample is a struct that represents a generated cURL example.

type ContextHandler

type ContextHandler struct {
	*BaseHandler
	// contains filtered or unexported fields
}

ContextHandler handles context routes.

type ContextListResponse

type ContextListResponse struct {
	Items []string `json:"items"`
}

ContextListResponse is a response for context list.

type Document

type Document interface {
	Provider() SchemaProvider
	GetVersion() string
	GetResources() map[string][]string
	FindOperation(options *OperationDescription) Operationer
}

Document is an interface that represents an OpenAPI document needed for content generation. It is implemented by the LibV2Document and LibV3Document types.

func NewKinDocumentFromFile

func NewKinDocumentFromFile(filePath string) (Document, error)

NewKinDocumentFromFile creates a new KinDocument from a file path

func NewLibOpenAPIDocumentFromFile

func NewLibOpenAPIDocumentFromFile(filePath string) (Document, error)

NewLibOpenAPIDocumentFromFile creates a new Document from a file path. It uses libopenapi to parse the file and then builds a model. Circular references are handled by logging the error and returning Document without errors.

type EditorConfig

type EditorConfig struct {
	Theme    string `koanf:"theme" json:"theme" yaml:"theme"`
	FontSize int    `koanf:"fontSize" json:"fontSize" yaml:"fontSize"`
}

type FakeFunc

type FakeFunc func() MixedValue

FakeFunc is a function that returns a MixedValue. This is u unified way to work with different return types from fake library.

type FakeFuncFactoryWithString

type FakeFuncFactoryWithString func(value string) FakeFunc

FakeFuncFactoryWithString is a function that returns a FakeFunc.

type FileProperties

type FileProperties struct {
	// ServiceName is the name of the service that the file belongs to.
	// It represents the first directory in the file path.
	ServiceName string

	// IsOpenAPI indicates whether the file is an OpenAPI specification.
	IsOpenAPI bool

	// Method is the HTTP method of the resource, which this file describes.
	Method string

	// Prefix is the path prefix of the resource, which this file describes.
	// This is service name with a leading slash.
	Prefix string

	// Resource is the path of the resource, which this file describes without prefix.
	Resource string

	// FilePath is the full path to the file.
	FilePath string

	// FileName is the name of the file with the extension.
	FileName string

	// Extension is the extension of the file, with the leading dot.
	Extension string

	// ContentType is the MIME type of the file.
	ContentType string

	// Spec is the OpenAPI specification of the file if the file iis an OpenAPI specification.
	Spec Document `json:"-"`
}

FileProperties contains inferred properties of a file that is being loaded from service directory.

func GetPropertiesFromFilePath

func GetPropertiesFromFilePath(filePath string, appCfg *AppConfig) (*FileProperties, error)

GetPropertiesFromFilePath gets properties of a file from its path.

func (*FileProperties) IsEqual

func (f *FileProperties) IsEqual(other *FileProperties) bool

IsEqual compares two FileProperties structs. Spec is not compared.

type Float64Value

type Float64Value float64

func (Float64Value) Get

func (f Float64Value) Get() any

type GenerateResponse

type GenerateResponse struct {
	Request  *Request  `json:"request"`
	Response *Response `json:"response"`
}

type HomeHandler

type HomeHandler struct {
	*BaseHandler
	// contains filtered or unexported fields
}

HomeHandler handles home routes.

type IntValue

type IntValue int

func (IntValue) Get

func (i IntValue) Get() any

type JSONResponse

type JSONResponse struct {
	*BaseResponse
}

JSONResponse is a response type for JSON responses.

func NewJSONResponse

func NewJSONResponse(w http.ResponseWriter) *JSONResponse

NewJSONResponse creates a new JSONResponse instance.

func (*JSONResponse) Send

func (r *JSONResponse) Send(data any)

Send sends the data as JSON to the client. WriteHeader must be called before any writing happens and just once.

func (*JSONResponse) WithHeader

func (r *JSONResponse) WithHeader(key string, value string) *JSONResponse

WithHeader adds a header to the response.

func (*JSONResponse) WithStatusCode

func (r *JSONResponse) WithStatusCode(code int) *JSONResponse

WithStatusCode sets the status code of the response.

type KinDocument

type KinDocument struct {
	*openapi3.T
}

KinDocument is a wrapper around openapi3.T Implements Document interface

func (*KinDocument) FindOperation

func (d *KinDocument) FindOperation(options *OperationDescription) Operationer

FindOperation finds an operation by resource and method.

func (*KinDocument) GetResources

func (d *KinDocument) GetResources() map[string][]string

GetResources returns a map of resource names and their methods.

func (*KinDocument) GetVersion

func (d *KinDocument) GetVersion() string

GetVersion returns the version of the document

func (*KinDocument) Provider

func (d *KinDocument) Provider() SchemaProvider

Provider returns the SchemaProvider for this document

type KinOperation

type KinOperation struct {
	*openapi3.Operation
	// contains filtered or unexported fields
}

KinOperation is a wrapper around openapi3.Operation

func (*KinOperation) GetParameters

func (op *KinOperation) GetParameters() OpenAPIParameters

GetParameters returns the operation parameters

func (*KinOperation) GetRequestBody

func (op *KinOperation) GetRequestBody() (*Schema, string)

GetRequestBody returns the operation request body

func (*KinOperation) GetResponse

func (op *KinOperation) GetResponse() *OpenAPIResponse

GetResponse returns the operation response

func (*KinOperation) ID

func (op *KinOperation) ID() string

ID returns the operation ID

func (*KinOperation) WithParseConfig

func (op *KinOperation) WithParseConfig(config *ParseConfig) Operationer

WithParseConfig sets the parse config for this operation

type LibV2Document

type LibV2Document struct {
	*libopenapi.DocumentModel[v2high.Swagger]
	ParseConfig *ParseConfig
}

LibV2Document is a wrapper around libopenapi.DocumentModel Implements Document interface

func (*LibV2Document) FindOperation

func (d *LibV2Document) FindOperation(options *OperationDescription) Operationer

FindOperation finds an operation by resource and method.

func (*LibV2Document) GetResources

func (d *LibV2Document) GetResources() map[string][]string

GetResources returns a map of resource names and their methods.

func (*LibV2Document) GetVersion

func (d *LibV2Document) GetVersion() string

GetVersion returns the version of the document

func (*LibV2Document) Provider

func (d *LibV2Document) Provider() SchemaProvider

Provider returns the SchemaProvider for this document

type LibV2Operation

type LibV2Operation struct {
	*v2high.Operation
	ParseConfig *ParseConfig
	// contains filtered or unexported fields
}

LibV2Operation is a wrapper around libopenapi.Operation

func (*LibV2Operation) GetParameters

func (op *LibV2Operation) GetParameters() OpenAPIParameters

GetParameters returns a list of parameters for this operation

func (*LibV2Operation) GetRequestBody

func (op *LibV2Operation) GetRequestBody() (*Schema, string)

GetRequestBody returns the request body for this operation

func (*LibV2Operation) GetResponse

func (op *LibV2Operation) GetResponse() *OpenAPIResponse

GetResponse returns the response for this operation

func (*LibV2Operation) ID

func (op *LibV2Operation) ID() string

ID returns the operation ID

func (*LibV2Operation) WithParseConfig

func (op *LibV2Operation) WithParseConfig(parseConfig *ParseConfig) Operationer

WithParseConfig sets the ParseConfig for the operation

type LibV3Document

type LibV3Document struct {
	*libopenapi.DocumentModel[v3high.Document]
}

LibV3Document is a wrapper around libopenapi.DocumentModel Implements Document interface

func (*LibV3Document) FindOperation

func (d *LibV3Document) FindOperation(options *OperationDescription) Operationer

FindOperation finds an operation by resource and method.

func (*LibV3Document) GetResources

func (d *LibV3Document) GetResources() map[string][]string

GetResources returns a map of resource names and their methods.

func (*LibV3Document) GetVersion

func (d *LibV3Document) GetVersion() string

GetVersion returns the version of the document

func (*LibV3Document) Provider

func (d *LibV3Document) Provider() SchemaProvider

Provider returns the SchemaProvider for this document

type LibV3Operation

type LibV3Operation struct {
	*v3high.Operation
	// contains filtered or unexported fields
}

LibV3Operation is a wrapper around libopenapi.Operation

func (*LibV3Operation) GetParameters

func (op *LibV3Operation) GetParameters() OpenAPIParameters

GetParameters returns a list of parameters for the operation

func (*LibV3Operation) GetRequestBody

func (op *LibV3Operation) GetRequestBody() (*Schema, string)

GetRequestBody returns the request body for the operation.

func (*LibV3Operation) GetResponse

func (op *LibV3Operation) GetResponse() *OpenAPIResponse

GetResponse returns the response for the operation. If no response is defined, a default response is returned. Responses are prioritized by status code, with 200 being the highest priority.

func (*LibV3Operation) ID

func (op *LibV3Operation) ID() string

ID returns the operation ID

func (*LibV3Operation) WithParseConfig

func (op *LibV3Operation) WithParseConfig(parseConfig *ParseConfig) Operationer

WithParseConfig sets the ParseConfig for the operation.

type MemoryStorage

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

MemoryStorage is a cache storage that stores data in memory.

func NewMemoryStorage

func NewMemoryStorage() *MemoryStorage

NewMemoryStorage creates a new MemoryStorage instance.

func (*MemoryStorage) Get

func (s *MemoryStorage) Get(key string) (any, bool)

Get returns the value for the given key.

func (*MemoryStorage) Set

func (s *MemoryStorage) Set(key string, value any) error

Set sets the value for the given key.

type MixedValue

type MixedValue interface {
	Get() any
}

MixedValue is a value that can represent string, int, float64, or bool type.

type OpenAPIHandler

type OpenAPIHandler struct {
	*BaseHandler
	// contains filtered or unexported fields
}

OpenAPIHandler handles OpenAPI routes serve.

type OpenAPIHeaders

type OpenAPIHeaders map[string]*OpenAPIParameter

OpenAPIHeaders is a map of OpenAPIParameter.

type OpenAPIParameter

type OpenAPIParameter struct {
	Name     string      `json:"name,omitempty" yaml:"name,omitempty"`
	In       string      `json:"in,omitempty" yaml:"in,omitempty"`
	Required bool        `json:"required,omitempty" yaml:"required,omitempty"`
	Schema   *Schema     `json:"schema,omitempty" yaml:"schema,omitempty"`
	Example  interface{} `json:"example,omitempty" yaml:"example,omitempty"`
}

OpenAPIParameter is a struct that represents an OpenAPI parameter.

type OpenAPIParameters

type OpenAPIParameters []*OpenAPIParameter

OpenAPIParameters is a slice of OpenAPIParameter.

type OpenAPIResponse

type OpenAPIResponse struct {
	Headers     OpenAPIHeaders
	Content     *Schema
	ContentType string
	StatusCode  int
}

OpenAPIResponse is a struct that represents an OpenAPI response.

type OperationDescription

type OperationDescription struct {
	Service  string
	Resource string
	Method   string
}

OperationDescription is a struct that used to find an operation in an OpenAPI document.

type Operationer

type Operationer interface {
	ID() string
	GetParameters() OpenAPIParameters
	GetRequestBody() (*Schema, string)
	GetResponse() *OpenAPIResponse
	WithParseConfig(*ParseConfig) Operationer
}

Operationer is an interface that represents an OpenAPI operation needed for content generation.

func NewCacheOperationAdapter

func NewCacheOperationAdapter(service string, operation Operationer, storage CacheStorage) Operationer

NewCacheOperationAdapter creates a new CacheOperationAdapter instance.

type ParseConfig

type ParseConfig struct {
	// MaxLevels is the maximum level to parse.
	MaxLevels int `koanf:"maxLevels" json:"maxLevels" yaml:"maxLevels"`

	// MaxRecursionLevels is the maximum level to parse recursively.
	// 0 means no recursion: property will get nil value.
	MaxRecursionLevels int `koanf:"maxRecursionLevels" json:"maxRecursionLevels" yaml:"maxRecursionLevels"`

	// OnlyRequired is a flag whether to include only required fields.
	// If the spec contains deep references, this might significantly speed up parsing.
	OnlyRequired bool `koanf:"onlyRequired" json:"onlyRequired" yaml:"onlyRequired"`
}

func NewParseConfig added in v0.1.8

func NewParseConfig() *ParseConfig

type ParsedContextResult

type ParsedContextResult struct {
	Result  map[string]any
	Aliases map[string]string
}

ParsedContextResult is the result of parsing a context file.

func ParseContextFile

func ParseContextFile(filePath string, fakes map[string]FakeFunc) (*ParsedContextResult, error)

ParseContextFile parses a YAML file and returns a map of context properties. Filename without extension is used as the context namespace and can be referenced: - in service config - when creating aliases

func ParseContextFromBytes

func ParseContextFromBytes(content []byte, fakes map[string]FakeFunc) (*ParsedContextResult, error)

ParseContextFromBytes byte contents from the YAML file and returns a map of context properties.

type Paths

type Paths struct {
	Base              string
	Resources         string
	Data              string
	Contexts          string
	Docs              string
	Samples           string
	Services          string
	ServicesOpenAPI   string
	ServicesFixedRoot string
	UI                string
	ConfigFile        string
}

Paths is a struct that holds all the paths used by the application.

func NewPaths

func NewPaths(baseDir string) *Paths

type ReplaceContext

type ReplaceContext struct {
	// Schema is a schema that is used to replace values.
	// Currently only OpenAPI Schema is supported.
	// It does not depend on schema provider as this is already converted to internal Schema type.
	Schema any

	// State is a state of the current replace operation.
	// It is used to store information about the current element, including its name, index, content type etc.
	State *ReplaceState

	// AreaPrefix is a prefix that is used to identify the correct section
	// in the context config for specific replacement area.
	// e.g. in-
	// then in the contexts we should have:
	// in-header:
	//   X-Request-ID: 123
	// in-path:
	//   user_id: 123
	AreaPrefix string

	// Data is a list of contexts that are used to replace values.
	Data []map[string]any

	// Faker is a faker instance that is used to generate fake data.
	Faker faker.Faker
}

type ReplaceState

type ReplaceState struct {
	// NamePath is a slice of names of the current element.
	// It is used to build a path to the current element.
	// For example, "users", "name", "first".
	NamePath []string

	// ElementIndex is an index of the current element if required structure to generate is an array.
	ElementIndex int

	// IsHeader is a flag that indicates that the current element we're replacing is a header.
	IsHeader bool

	// IsPathParam is a flag that indicates that the current element we're replacing is a path parameter.
	IsPathParam bool

	// ContentType is a content type of the current element.
	ContentType string

	// IsContentReadOnly is a flag that indicates that the current element we're replacing is a read-only content.
	// This value is used only when Schema has ReadOnly set to true.
	IsContentReadOnly bool

	// IsContentWriteOnly is a flag that indicates that the current element we're replacing is a write-only content.
	// This value is used only when Schema has WriteOnly set to true.
	IsContentWriteOnly bool
	// contains filtered or unexported fields
}

ReplaceState is a struct that holds information about the current state of the replace operation.

func NewReplaceState added in v0.1.4

func NewReplaceState(opts ...ReplaceStateOption) *ReplaceState

func NewReplaceStateWithName added in v0.1.4

func NewReplaceStateWithName(name string) *ReplaceState

func (*ReplaceState) NewFrom

func (s *ReplaceState) NewFrom(src *ReplaceState) *ReplaceState

NewFrom creates a new ReplaceState instance from the given one.

func (*ReplaceState) WithOptions added in v0.1.4

func (s *ReplaceState) WithOptions(options ...ReplaceStateOption) *ReplaceState

type ReplaceStateOption added in v0.1.4

type ReplaceStateOption func(*ReplaceState)

func WithContentType added in v0.1.4

func WithContentType(value string) ReplaceStateOption

func WithElementIndex added in v0.1.4

func WithElementIndex(value int) ReplaceStateOption

func WithHeader added in v0.1.4

func WithHeader() ReplaceStateOption

func WithName added in v0.1.4

func WithName(name string) ReplaceStateOption

func WithPath added in v0.1.4

func WithPath() ReplaceStateOption

func WithReadOnly added in v0.1.4

func WithReadOnly() ReplaceStateOption

func WithWriteOnly added in v0.1.4

func WithWriteOnly() ReplaceStateOption

type Replacer

type Replacer func(ctx *ReplaceContext) any

Replacer is a function that returns a value to replace the original value with. Replacer functions are predefined and set in the correct order to be executed.

type Request

type Request struct {
	Headers     any             `json:"headers,omitempty"`
	Method      string          `json:"method,omitempty"`
	Path        string          `json:"path,omitempty"`
	Query       any             `json:"query,omitempty"`
	Body        string          `json:"body,omitempty"`
	ContentType string          `json:"contentType,omitempty"`
	Examples    *ContentExample `json:"examples,omitempty"`
}

Request is a struct that represents a generated request to be used when building real endpoint request.

func NewRequestFromOperation

func NewRequestFromOperation(pathPrefix, path, method string, operation Operationer, valueReplacer ValueReplacer) *Request

NewRequestFromOperation creates a new request from an operation. It used to pre-generate payloads from the UI or provide service to generate such. It's not part of OpenAPI endpoint handler.

type ResourceGeneratePayload

type ResourceGeneratePayload struct {
	Replacements map[string]any `json:"replacements"`
}

ResourceGeneratePayload is a payload for generating resources. It contains a map of replacements. It is used only with generating resources endpoint. It's merged together with contexts but has higher priority.

type ResourceResponse

type ResourceResponse struct {
	Method      string `json:"method"`
	Path        string `json:"path"`
	Extension   string `json:"extension"`
	ContentType string `json:"contentType"`
	Content     string `json:"content"`
}

type Response

type Response struct {
	Headers     http.Header `json:"headers,omitempty"`
	Content     []byte      `json:"content,omitempty"`
	ContentType string      `json:"contentType,omitempty"`
	StatusCode  int         `json:"statusCode,omitempty"`
}

Response is a struct that represents a generated response to be used when comparing real endpoint response.

func NewResponseFromOperation

func NewResponseFromOperation(operation Operationer, valueReplacer ValueReplacer) *Response

NewResponseFromOperation creates a new response from an operation. It used to pre-generate payloads from the UI or provide service to generate such.

type RouteDescription

type RouteDescription struct {
	Method      string          `json:"method"`
	Path        string          `json:"path"`
	Type        string          `json:"type"`
	ContentType string          `json:"contentType"`
	Overwrites  bool            `json:"overwrites"`
	File        *FileProperties `json:"-"`
}

RouteDescription describes a route for the UI Application. Path is relative to the service prefix.

type RouteDescriptions

type RouteDescriptions []*RouteDescription

RouteDescriptions is a slice of RouteDescription. Allows to add custom methods.

func (RouteDescriptions) Sort

func (rs RouteDescriptions) Sort()

Sort sorts the routes by path and method. The order is: GET, POST, other methods (alphabetically)

type RouteRegister

type RouteRegister func(router *Router) error

type Router

type Router struct {
	*chi.Mux

	// Config is a pointer to the global Config instance.
	Config *Config
	// contains filtered or unexported fields
}

Router is a wrapper around chi.Mux that adds some extra functionality.

func NewRouter

func NewRouter(config *Config) *Router

NewRouter creates a new Router instance from Config.

func (*Router) AddService added in v0.0.54

func (r *Router) AddService(item *ServiceItem)

func (*Router) GetContexts added in v0.0.54

func (r *Router) GetContexts() map[string]map[string]any

func (*Router) GetDefaultContexts added in v0.0.54

func (r *Router) GetDefaultContexts() []map[string]string

func (*Router) GetServices added in v0.0.54

func (r *Router) GetServices() map[string]*ServiceItem

func (*Router) RemoveContext

func (r *Router) RemoveContext(name string)

RemoveContext removes registered context namespace from the router. Removing it from the service configurations seems not needed at the moment as it won't affect any resolving.

func (*Router) RemoveService added in v0.1.1

func (r *Router) RemoveService(name string)

func (*Router) SetContexts added in v0.0.54

func (r *Router) SetContexts(contexts map[string]map[string]any, defaultContexts []map[string]string) *Router

func (*Router) SetServices added in v0.0.54

func (r *Router) SetServices(services map[string]*ServiceItem) *Router

type SavedResourceResponse

type SavedResourceResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
	ID      int    `json:"id"`
}

type Schema

type Schema struct {
	Type string `json:"type,omitempty" yaml:"type,omitempty"`

	// in 3.1 examples can be an array (which is recommended)
	Examples []any `json:"examples,omitempty" yaml:"examples,omitempty"`

	// items can be a schema in 2.0, 3.0 and 3.1 or a bool in 3.1
	Items *Schema `json:"items,omitempty" yaml:"items,omitempty"`

	// Compatible with all versions
	MultipleOf    float64            `json:"multipleOf,omitempty" yaml:"multipleOf,omitempty"`
	Maximum       float64            `json:"maximum,omitempty" yaml:"maximum,omitempty"`
	Minimum       float64            `json:"minimum,omitempty" yaml:"minimum,omitempty"`
	MaxLength     int64              `json:"maxLength,omitempty" yaml:"maxLength,omitempty"`
	MinLength     int64              `json:"minLength,omitempty" yaml:"minLength,omitempty"`
	Pattern       string             `json:"pattern,omitempty" yaml:"pattern,omitempty"`
	Format        string             `json:"format,omitempty" yaml:"format,omitempty"`
	MaxItems      int64              `json:"maxItems,omitempty" yaml:"maxItems,omitempty"`
	MinItems      int64              `json:"minItems,omitempty" yaml:"minItems,omitempty"`
	MaxProperties int64              `json:"maxProperties,omitempty" yaml:"maxProperties,omitempty"`
	MinProperties int64              `json:"minProperties,omitempty" yaml:"minProperties,omitempty"`
	Required      []string           `json:"required,omitempty" yaml:"required,omitempty"`
	Enum          []any              `json:"enum,omitempty" yaml:"enum,omitempty"`
	Properties    map[string]*Schema `json:"properties,omitempty" yaml:"properties,omitempty"`
	Not           *Schema            `json:"not,omitempty" yaml:"not,omitempty"`
	Default       any                `json:"default,omitempty" yaml:"default,omitempty"`
	Nullable      bool               `json:"nullable,omitempty" yaml:"nullable,omitempty"`
	ReadOnly      bool               `json:"readOnly,omitempty" yaml:"readOnly,omitempty"`
	WriteOnly     bool               `json:"writeOnly,omitempty" yaml:"writeOnly,omitempty"`
	Example       any                `json:"example,omitempty" yaml:"example,omitempty"`
	Deprecated    bool               `json:"deprecated,omitempty" yaml:"deprecated,omitempty"`
}

Schema is a struct that represents an OpenAPI schema. It is compatible with all versions of OpenAPI. All schema providers should implement the Document and Operationer interfaces. This provides a unified way to work with different OpenAPI parsers.

func NewSchemaFromKin

func NewSchemaFromKin(schema *openapi3.Schema, parseConfig *ParseConfig) *Schema

NewSchemaFromKin creates a new Schema from a Kin schema

func NewSchemaFromLibOpenAPI

func NewSchemaFromLibOpenAPI(schema *base.Schema, parseConfig *ParseConfig) *Schema

NewSchemaFromLibOpenAPI creates a new Schema from a libopenapi Schema.

type SchemaProvider

type SchemaProvider string
const (
	KinOpenAPIProvider    SchemaProvider = "kin-openapi"
	LibOpenAPIProvider    SchemaProvider = "libopenapi"
	DefaultSchemaProvider SchemaProvider = LibOpenAPIProvider
)

type SchemaWithContentType

type SchemaWithContentType struct {
	Schema      *Schema
	ContentType string
}

SchemaWithContentType is a schema with a content type. It is used to cache the result of GetRequestBody and wrap 2 values together.

type ServiceCacheConfig

type ServiceCacheConfig struct {
	// Avoid multiple schema parsing by caching the parsed schema.
	// Default: true
	Schema bool `koanf:"schema" json:"schema" yaml:"schema"`
}

func NewServiceCacheConfig added in v0.1.8

func NewServiceCacheConfig() *ServiceCacheConfig

type ServiceConfig

type ServiceConfig struct {
	// Latency is the latency to add to the response.
	// Latency not used in the services API, only when endpoint queried directly.
	Latency time.Duration `koanf:"latency" json:"latency" yaml:"latency"`

	// Errors is the error config.
	Errors *ServiceError `koanf:"errors" json:"errors" yaml:"errors"`

	// Contexts is the list of contexts to use for replacements.
	// It is a map of context name defined either in the UI or filename without extension.
	// You can refer to the name when building aliases.
	Contexts []map[string]string `koanf:"contexts" json:"contexts" yaml:"contexts"`

	// ParseConfig is the config for parsing the OpenAPI spec.
	ParseConfig *ParseConfig `json:"parseConfig" yaml:"parseConfig" koanf:"parseConfig"`

	// Validate is the validation config.
	// It is used to validate the request and/or response outside of the Services API.
	Validate *ServiceValidateConfig `koanf:"validate" json:"validate" yaml:"validate"`

	// Cache is the cache config.
	Cache *ServiceCacheConfig `koanf:"cache" json:"cache" yaml:"cache"`
}

func NewServiceConfig added in v0.1.8

func NewServiceConfig() *ServiceConfig

type ServiceDescription

type ServiceDescription struct {
	Method    string
	Path      string
	Ext       string
	IsOpenAPI bool
}

ServiceDescription is a struct created from the service payload to facilitate file path composition.

type ServiceEmbedded

type ServiceEmbedded struct {
	Name string `json:"name"`
}

type ServiceError

type ServiceError struct {
	// Chance is the chance to return an error.
	// In the config, it can be set with %-suffix.
	Chance int `koanf:"chance" json:"chance" yaml:"chance"`

	// Codes is a map of error codes and their weights if Chance > 0.
	// If no error codes are specified, it returns a 500 error code.
	Codes map[int]int `koanf:"codes" json:"codes" yaml:"codes"`
	// contains filtered or unexported fields
}

func NewServiceErrorConfig added in v0.1.8

func NewServiceErrorConfig() *ServiceError

func (*ServiceError) GetError

func (s *ServiceError) GetError() int

GetError returns an error code based on the chance and error weights. If no error weights are specified, it returns a 500 error code. If the chance is 0, it returns 0.

type ServiceHandler

type ServiceHandler struct {
	*BaseHandler
	// contains filtered or unexported fields
}

ServiceHandler handles service routes.

type ServiceItem

type ServiceItem struct {
	Name         string            `json:"name"`
	Routes       RouteDescriptions `json:"routes"`
	OpenAPIFiles []*FileProperties `json:"-"`
	// contains filtered or unexported fields
}

ServiceItem represents a service with the route collection. Service can hold multiple OpenAPI specs.

func (*ServiceItem) AddOpenAPIFile

func (i *ServiceItem) AddOpenAPIFile(file *FileProperties)

AddOpenAPIFile adds OpenAPI file to the service.

func (*ServiceItem) AddRoutes

func (i *ServiceItem) AddRoutes(routes RouteDescriptions)

AddRoutes adds routes to the service. There's no check for duplicates.

type ServiceItemResponse

type ServiceItemResponse struct {
	Name             string   `json:"name"`
	OpenAPIResources []string `json:"openApiResources"`
}

type ServiceListResponse

type ServiceListResponse struct {
	Items []*ServiceItemResponse `json:"items"`
}

type ServicePayload

type ServicePayload struct {
	IsOpenAPI   bool          `json:"isOpenApi"`
	Method      string        `json:"method"`
	Path        string        `json:"path"`
	Response    []byte        `json:"response"`
	ContentType string        `json:"contentType"`
	File        *UploadedFile `json:"file"`
	URL         string        `json:"url"`
}

ServicePayload is a struct that represents a new service payload.

type ServiceResourcesResponse

type ServiceResourcesResponse struct {
	Service          *ServiceEmbedded  `json:"service"`
	Endpoints        RouteDescriptions `json:"endpoints"`
	OpenAPISpecNames []string          `json:"openapiSpecNames"`
}

type ServiceValidateConfig

type ServiceValidateConfig struct {
	// Request is a flag whether to validate the request.
	// Default: true
	Request bool `koanf:"request" json:"request" yaml:"request"`

	// Response is a flag whether to validate the response.
	// Default: false
	Response bool `koanf:"response" json:"response" yaml:"response"`
}

func NewServiceValidateConfig added in v0.1.8

func NewServiceValidateConfig() *ServiceValidateConfig

type SettingsHandler

type SettingsHandler struct {
	*BaseHandler
	// contains filtered or unexported fields
}

SettingsHandler handles settings routes.

type SimpleResponse

type SimpleResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
}

SimpleResponse is a simple response type to indicate the success of an operation.

type StringValue

type StringValue string

func (StringValue) Get

func (s StringValue) Get() any

type UploadedFile

type UploadedFile struct {
	// Content is the content of the file.
	Content []byte

	// Filename is the name of the file.
	Filename string

	// Extension is the extension of the file with the leading dot.
	Extension string

	// Size is the size of the file in bytes.
	Size int64
}

UploadedFile represents an uploaded file.

func GetRequestFile

func GetRequestFile(r *http.Request, fieldName string) (*UploadedFile, error)

GetRequestFile gets an uploaded file from a request.

type ValueReplacer

type ValueReplacer func(schemaOrContent any, state *ReplaceState) any

ValueReplacer is a function that replaces value in schema or content. This function should encapsulate all the logic, data, contexts etc. of replacing values.

func CreateValueReplacer

func CreateValueReplacer(cfg *Config, contexts []map[string]any) ValueReplacer

CreateValueReplacer is a factory that creates a new ValueReplacer instance from the given config and contexts.

Jump to

Keyboard shortcuts

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