api

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2025 License: MIT Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OpenAPIRouteType = "openapi"
	FixedRouteType   = "fixed"
)

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")
	ErrOnlyFixedResourcesAllowedEditing = errors.New("only fixed resources are allowed editing")
	ErrGettingFileFromURL               = errors.New("error getting file from url")
)

Functions

func ComposeFileSavePath

func ComposeFileSavePath(descr *ServiceDescription, paths *config.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.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 CreateAfterHandlerMiddleware added in v0.1.61

func CreateAfterHandlerMiddleware(params *MiddlewareParams) func(http.Handler) http.Handler

CreateAfterHandlerMiddleware is a method on the Router to create a middleware

func CreateBeforeHandlerMiddleware added in v0.1.61

func CreateBeforeHandlerMiddleware(params *MiddlewareParams) func(http.Handler) http.Handler

CreateBeforeHandlerMiddleware returns a middleware that modifies the request. Function names must be defined in the service configuration middleware config and refer to compiled plugin.

func CreateCacheRequestMiddleware added in v0.1.42

func CreateCacheRequestMiddleware(params *MiddlewareParams) func(http.Handler) http.Handler

CreateCacheRequestMiddleware returns a middleware that checks if GET request is cached in history. Depends on service settings. Service timeouts still apply.

func CreateUpstreamRequestMiddleware

func CreateUpstreamRequestMiddleware(params *MiddlewareParams) func(http.Handler) http.Handler

CreateUpstreamRequestMiddleware returns a middleware that fetches data from an upstream service. If the upstream service fails, consequent requests will be blocked for a certain time.

func GetJSONPayload

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

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

func HandleErrorAndLatency

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

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

func MustFileStructure

func MustFileStructure(paths *config.Paths) error

MustFileStructure creates the necessary directories and files

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 App

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

App is the main application struct

func NewApp

func NewApp(config *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 BaseHandler

type BaseHandler struct {
}

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

func NewBaseHandler

func NewBaseHandler() *BaseHandler

func (*BaseHandler) Error

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

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 BufferedWriter

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

func NewBufferedResponseWriter() *BufferedWriter

NewBufferedResponseWriter creates a new buffered writer.

func (*BufferedWriter) Header

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

Header returns the header.

func (*BufferedWriter) Write

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

Write writes the data to the buffer.

func (*BufferedWriter) WriteHeader

func (bw *BufferedWriter) WriteHeader(statusCode int)

WriteHeader writes the status code.

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 CurrentRequestStorage

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

CurrentRequestStorage is a storage for requests.

func NewCurrentRequestStorage

func NewCurrentRequestStorage(clearTimeout time.Duration) *CurrentRequestStorage

NewCurrentRequestStorage creates a new CurrentRequestStorage instance. It also starts a goroutine that clears the storage every clearTimeout duration.

func (*CurrentRequestStorage) Cancel

func (s *CurrentRequestStorage) Cancel()

Cancel stops the goroutine that clears the storage

func (*CurrentRequestStorage) Clear

func (s *CurrentRequestStorage) Clear()

Clear removes all keys from the storage

func (*CurrentRequestStorage) Get

Get retrieves a value from the storage

func (*CurrentRequestStorage) Set

Set adds or updates a value in the storage

func (*CurrentRequestStorage) SetResponse

func (s *CurrentRequestStorage) SetResponse(request *http.Request, response *connexions_plugin.HistoryResponse)

SetResponse updates response value in the storage

type GenerateResponse

type GenerateResponse struct {
	Request  *openapi.GeneratedRequest  `json:"request"`
	Response *openapi.GeneratedResponse `json:"response"`
}

type HomeHandler

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

HomeHandler handles home routes.

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 MemoryStorage added in v0.1.69

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

func NewMemoryStorage added in v0.1.69

func NewMemoryStorage() *MemoryStorage

func (*MemoryStorage) Data added in v0.1.71

func (s *MemoryStorage) Data() map[string]any

func (*MemoryStorage) Get added in v0.1.69

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

func (*MemoryStorage) Set added in v0.1.69

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

type MiddlewareParams

type MiddlewareParams struct {
	ServiceConfig  *config.ServiceConfig
	Service        string
	Resource       string
	ResourcePrefix string
	Plugin         *plugin.Plugin
	// contains filtered or unexported fields
}

type OpenAPIHandler

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

OpenAPIHandler handles OpenAPI routes serve.

type PostmanBody added in v1.1.0

type PostmanBody struct {
	Mode       string              `json:"mode"`
	Raw        string              `json:"raw"`
	Options    *PostmanBodyOptions `json:"options"`
	FormData   []*PostmanKeyValue  `json:"formData,omitempty"`
	Urlencoded []*PostmanKeyValue  `json:"urlencoded,omitempty"`
}

type PostmanBodyOptions added in v1.1.0

type PostmanBodyOptions struct {
	Raw *PostmanRawBody `json:"raw"`
}

type PostmanCollection added in v1.1.0

type PostmanCollection struct {
	Info *PostmanInfo   `json:"info"`
	Item []*PostmanItem `json:"item"`
}

type PostmanEnvironment added in v1.1.0

type PostmanEnvironment struct {
	ID                   string             `json:"id"`
	Name                 string             `json:"name"`
	Values               []*PostmanKeyValue `json:"values"`
	PostmanVariableScope string             `json:"_postman_variable_scope"`
	PostmanExportedAt    string             `json:"_postman_exported_at"`
	PostmanExportedUsing string             `json:"_postman_exported_using"`
}

type PostmanInfo added in v1.1.0

type PostmanInfo struct {
	Name    string `json:"name"`
	Postman string `json:"_postman_id"`
	Schema  string `json:"schema"`
}

type PostmanItem added in v1.1.0

type PostmanItem struct {
	Name     string             `json:"name"`
	Request  *PostmanRequest    `json:"request,omitempty"`
	Response []*PostmanResponse `json:"response,omitempty"`
	Item     []*PostmanItem     `json:"item,omitempty"`
}

type PostmanKeyValue added in v1.1.0

type PostmanKeyValue struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

type PostmanRawBody added in v1.1.0

type PostmanRawBody struct {
	Language string `json:"language"`
}

type PostmanRequest added in v1.1.0

type PostmanRequest struct {
	Method string             `json:"method"`
	Header []*PostmanKeyValue `json:"header"`
	Body   *PostmanBody       `json:"body,omitempty"`
	URL    *PostmanURL        `json:"url,omitempty"`
}

type PostmanResponse added in v1.1.0

type PostmanResponse struct {
}

type PostmanURL added in v1.1.0

type PostmanURL struct {
	Raw      string             `json:"raw"`
	Host     []string           `json:"host"`
	Path     []string           `json:"path"`
	Query    []*PostmanKeyValue `json:"query,omitempty"`
	Variable []*PostmanKeyValue `json:"variable,omitempty"`
}

type ResourceGeneratePayload

type ResourceGeneratePayload struct {
	Service      string         `json:"service"`
	Resource     string         `json:"resource"`
	Method       string         `json:"method"`
	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 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        *openapi.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 *config.Config
	// contains filtered or unexported fields
}

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

Config is a pointer to the global Config instance. services: Router keeps track of registered services and their routes. contexts is a map of registered context namespaces. Each namespace is a map of context names and their values.

defaultContexts is a slice of registered context namespaces. It can refer to complete context namespace or just a part of it: e.g. in yaml config - common: - fake:payments

func NewRouter

func NewRouter(config *config.Config) *Router

NewRouter creates a new Router instance from Config.

func (*Router) AddService

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

func (*Router) GetContexts

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

func (*Router) GetDefaultContexts

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

func (*Router) GetServices

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

func (r *Router) RemoveService(name string)

func (*Router) SetContexts

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

func (*Router) SetServices

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 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 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 []*openapi.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 *openapi.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        *openapi.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 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.

Jump to

Keyboard shortcuts

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