api

package
v1.1.5 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2025 License: AGPL-3.0 Imports: 43 Imported by: 38

Documentation

Index

Constants

This section is empty.

Variables

View Source
var APIs = map[string]util.KV{}
View Source
var DefaultAPI = Handler{}

Functions

func AddGlobalInterceptors

func AddGlobalInterceptors(interceptors ...Interceptor)

func AutoIssueTLSCertificates

func AutoIssueTLSCertificates(tlsCfg *config.TLSConfig, cfg *tls.Config)

func BasicAuth

func BasicAuth(h httprouter.Handle, requiredUser, requiredPassword string) httprouter.Handle

BasicAuth register api with basic auth

func BypassCORSCheck added in v1.1.5

func BypassCORSCheck(next http.Handler) http.Handler

BypassCORSCheck wraps an HTTP handler to allow all origins

func DestroySession

func DestroySession(w http.ResponseWriter, r *http.Request) bool

DestroySession remove session by creating a new empty session

func EncodeJSON added in v1.1.4

func EncodeJSON(v interface{}) (b []byte, err error)

EncodeJSON encode the object to json string

func GetAppSetting

func GetAppSetting(key string) interface{}

func GetAppSettings

func GetAppSettings() util.MapStr

func GetClientTLSConfig

func GetClientTLSConfig(tlsConfig *config.TLSConfig) (*tls.Config, error)

func GetFastHttpClient added in v1.1.0

func GetFastHttpClient(name string) *fasthttp.Client

func GetFlash

func GetFlash(w http.ResponseWriter, r *http.Request) (bool, []interface{})

GetFlash get flash value

func GetHttpClient added in v1.1.0

func GetHttpClient(name string) *http.Client

func GetServerTLSConfig

func GetServerTLSConfig(tlsCfg *config.TLSConfig) (*tls.Config, error)

func GetSession

func GetSession(r *http.Request, key string) (bool, interface{})

GetSession return session by session key

func GetSessionStore

func GetSessionStore(r *http.Request, key string) (*sessions.Session, error)

func HandleAPIFunc

func HandleAPIFunc(pattern string, handler func(http.ResponseWriter, *http.Request))

HandleAPIFunc register api handler to specify pattern

func HandleAPIMethod

func HandleAPIMethod(method Method, pattern string, handler func(w http.ResponseWriter, req *http.Request, ps httprouter.Params))

HandleAPIMethod register api handler

func HandleUI

func HandleUI(pattern string, handler http.Handler)

HandleUI register ui request handler

func HandleUIMethod

func HandleUIMethod(method Method, pattern string, handler func(w http.ResponseWriter, req *http.Request, ps httprouter.Params), options ...Option)

HandleUIMethod register ui request handler

func HandleWebSocketCommand

func HandleWebSocketCommand(command string, usage string, handler func(c *websocket.WebsocketConnection, array []string))

HandleWebSocketCommand register websocket command handler

func IsAuthEnable

func IsAuthEnable() bool

TODO to be removed

func NewHTTPClient

func NewHTTPClient(clientCfg *config.HTTPClientConfig) (*http.Client, error)

func PrepareErrorJson added in v1.1.3

func PrepareErrorJson(errMessage string, statusCode int) util.MapStr

func RecoveryHandler

func RecoveryHandler(opts ...RecoveryOption) func(h http.Handler) http.Handler

RecoveryHandler is HTTP middleware that recovers from a panic, logs the panic, writes http.StatusInternalServerError, and continues to the next handler.

func RegisterAPIFilter

func RegisterAPIFilter(f filter.Filter)

func RegisterAppSetting

func RegisterAppSetting(key string, v interface{})

func RegisterUIFilter added in v1.1.4

func RegisterUIFilter(filter UIFilters)

RegisterUIFilter adds a filter to the chain (typically called during initialization)

func SetFlash

func SetFlash(w http.ResponseWriter, r *http.Request, msg string) bool

SetFlash set flash value

func SetNotFoundHandler

func SetNotFoundHandler(handler func(rw http.ResponseWriter, r *http.Request))

func SetSession

func SetSession(w http.ResponseWriter, r *http.Request, key string, value interface{}) bool

SetSession set session by session key and session value

func SimpleGetTLSConfig

func SimpleGetTLSConfig(tlsConfig *config.TLSConfig) *tls.Config

func StartAPI

func StartAPI()

StartAPI will start listen and act as the API server

func StartWeb

func StartWeb(cfg config.WebAppConfig)

func StopWeb

func StopWeb(cfg config.WebAppConfig)

func UpdateProxyEnvironment added in v1.1.0

func UpdateProxyEnvironment(cfg *config.ProxyConfig)

UpdateProxyEnvironment sets the system environment variables based on the ProxyConfig. It will override any existing environment variables with the new values provided in the config.

func WriteJSON added in v1.1.4

func WriteJSON(w http.ResponseWriter, v interface{}, statusCode int) error

Types

type AppSettings

type AppSettings struct {
	util.MapStr
	// contains filtered or unexported fields
}

func (*AppSettings) Add

func (settings *AppSettings) Add(key string, v interface{})

func (*AppSettings) Get

func (settings *AppSettings) Get(key string) interface{}

func (*AppSettings) GetSettingsMap

func (settings *AppSettings) GetSettingsMap() util.MapStr

type BasicAuthFilter

type BasicAuthFilter struct {
	Username string
	Password string
}

func (*BasicAuthFilter) FilterHttpHandlerFunc

func (filter *BasicAuthFilter) FilterHttpHandlerFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request)

func (*BasicAuthFilter) FilterHttpRouter

func (filter *BasicAuthFilter) FilterHttpRouter(pattern string, h httprouter.Handle) httprouter.Handle

type BasicTokenTransport

type BasicTokenTransport struct {
	Token     string
	Transport http.RoundTripper
}

func (*BasicTokenTransport) Client

func (t *BasicTokenTransport) Client() *http.Client

func (*BasicTokenTransport) RoundTrip

func (t *BasicTokenTransport) RoundTrip(req *http.Request) (*http.Response, error)

type FoundResp

type FoundResp struct {
	Found  bool        `json:"found"`
	Id     string      `json:"_id,omitempty"`
	Source interface{} `json:"_source,omitempty"`
}

func FoundResponse

func FoundResponse(id string, data interface{}) FoundResp

func NotFoundResponse

func NotFoundResponse(id string) FoundResp

type Handler

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

Handler is the object of http handler

func (Handler) DecodeJSON

func (handler Handler) DecodeJSON(r *http.Request, o interface{}) error

func (Handler) Error

func (handler Handler) Error(w http.ResponseWriter, err error)

Error output custom error

func (Handler) Error400

func (handler Handler) Error400(w http.ResponseWriter, msg string)

func (Handler) Error404

func (handler Handler) Error404(w http.ResponseWriter)

Error404 output 404 response

func (Handler) Error500

func (handler Handler) Error500(w http.ResponseWriter, msg string)

Error500 output 500 response

func (Handler) ErrorInternalServer

func (handler Handler) ErrorInternalServer(w http.ResponseWriter, msg string)

func (Handler) Flush

func (handler Handler) Flush(w http.ResponseWriter)

Flush flush response message

func (Handler) Get

func (handler Handler) Get(req *http.Request, key string, defaultValue string) string

Get http parameter or return default value

func (Handler) GetBoolOrDefault added in v1.1.2

func (handler Handler) GetBoolOrDefault(r *http.Request, key string, defaultValue bool) bool

func (Handler) GetHeader

func (handler Handler) GetHeader(req *http.Request, key string, defaultValue string) string

GetHeader return specify http header or return default value if not set

func (Handler) GetIntOrDefault

func (handler Handler) GetIntOrDefault(r *http.Request, key string, defaultValue int) int

GetIntOrDefault return parameter or default, data type is int

func (Handler) GetJSON

func (handler Handler) GetJSON(r *http.Request) (*jsonq.JsonQuery, error)

GetJSON return json input

func (Handler) GetParameter

func (handler Handler) GetParameter(r *http.Request, key string) string

GetParameter return query parameter with argument name

func (Handler) GetParameterOrDefault

func (handler Handler) GetParameterOrDefault(r *http.Request, key string, defaultValue string) string

GetParameterOrDefault return query parameter or return default value

func (Handler) GetRawBody

func (handler Handler) GetRawBody(r *http.Request) ([]byte, error)

GetRawBody return raw http request body

func (Handler) MustGetParameter

func (handler Handler) MustGetParameter(w http.ResponseWriter, r *http.Request, key string) string

func (Handler) Redirect

func (handler Handler) Redirect(w http.ResponseWriter, r *http.Request, url string)

func (Handler) Write

func (handler Handler) Write(w http.ResponseWriter, b []byte) (int, error)

Write response to client

func (Handler) WriteAckJSON

func (handler Handler) WriteAckJSON(w http.ResponseWriter, ack bool, status int, obj map[string]interface{}) error

func (Handler) WriteAckOKJSON

func (handler Handler) WriteAckOKJSON(w http.ResponseWriter) error

func (Handler) WriteAckWithMessage added in v1.1.5

func (handler Handler) WriteAckWithMessage(w http.ResponseWriter, ack bool, status int, msg string) error

func (Handler) WriteBytes added in v1.1.0

func (handler Handler) WriteBytes(w http.ResponseWriter, b []byte, statusCode int) error

func (Handler) WriteCreatedOKJSON

func (handler Handler) WriteCreatedOKJSON(w http.ResponseWriter, id interface{}) error

func (Handler) WriteDeletedOKJSON

func (handler Handler) WriteDeletedOKJSON(w http.ResponseWriter, id interface{}) error

func (Handler) WriteError

func (handler Handler) WriteError(w http.ResponseWriter, errMessage string, statusCode int) error

func (Handler) WriteErrorObject added in v1.1.4

func (handler Handler) WriteErrorObject(w http.ResponseWriter, err interface{}, status int)

func (Handler) WriteGetMissingJSON

func (handler Handler) WriteGetMissingJSON(w http.ResponseWriter, id string) error

func (Handler) WriteGetOKJSON

func (handler Handler) WriteGetOKJSON(w http.ResponseWriter, id, obj interface{}) error

func (Handler) WriteHeader

func (handler Handler) WriteHeader(w http.ResponseWriter, code int)

WriteHeader write status code to http header

func (Handler) WriteJSON

func (handler Handler) WriteJSON(w http.ResponseWriter, v interface{}, statusCode int) error

func (Handler) WriteJSONBytes added in v1.1.5

func (handler Handler) WriteJSONBytes(w http.ResponseWriter, b []byte, statusCode int) error

func (Handler) WriteJSONHeader

func (handler Handler) WriteJSONHeader(w http.ResponseWriter)

WriteJSONHeader will write standard json header

func (Handler) WriteJSONListResult

func (handler Handler) WriteJSONListResult(w http.ResponseWriter, total int64, v interface{}, statusCode int) error

WriteJSONListResult output result list to json format

func (Handler) WriteJavascriptHeader added in v1.1.5

func (handler Handler) WriteJavascriptHeader(w http.ResponseWriter)

func (Handler) WriteOKJSON

func (handler Handler) WriteOKJSON(w http.ResponseWriter, v interface{}) error

func (Handler) WriteTextHeader

func (handler Handler) WriteTextHeader(w http.ResponseWriter)

func (Handler) WriteUpdatedOKJSON

func (handler Handler) WriteUpdatedOKJSON(w http.ResponseWriter, id interface{}) error

type HandlerOptions added in v1.1.4

type HandlerOptions struct {
	RequireLogin      bool
	RequirePermission []string
	OptionLogin       bool
	Resource          string
	Action            string
	Name              string
	LogRequest        bool
	Labels            util.MapStr
	Features          map[string]bool
	Tags              []string
}

Define HandlerOptions to hold the state of all options

func (*HandlerOptions) Feature added in v1.1.5

func (option *HandlerOptions) Feature(feature string) bool

type Interceptor

type Interceptor interface {
	Match(request *http.Request) bool
	PreHandle(c ctx.Context, writer http.ResponseWriter, request *http.Request) (ctx.Context, error)
	PostHandle(c ctx.Context, writer http.ResponseWriter, request *http.Request)
	Name() string
}

type InterceptorHandler

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

func NewInterceptorHandler

func NewInterceptorHandler() *InterceptorHandler

func (*InterceptorHandler) AddInterceptors

func (i *InterceptorHandler) AddInterceptors(interceptors ...Interceptor)

func (*InterceptorHandler) Handler

func (i *InterceptorHandler) Handler(handler http.Handler) http.Handler

type Method

type Method string

Method is object of http method

const (
	// GET is http get method
	GET Method = "GET"
	// POST is http post method
	POST Method = "POST"
	// PUT is http put method
	PUT Method = "PUT"
	// DELETE is http delete method
	DELETE Method = "DELETE"
	// HEAD is http head method
	HEAD Method = "HEAD"

	OPTIONS Method = "OPTIONS"
)

func (Method) String

func (method Method) String() string

String return http method as string

type Option added in v1.1.4

type Option func(*HandlerOptions)

Define the Option type (function that modifies HandlerOptions)

func Action added in v1.1.5

func Action(action string) Option

func AllowPublicAccess added in v1.1.4

func AllowPublicAccess() Option

func Feature added in v1.1.5

func Feature(feature string) Option

func Label added in v1.1.5

func Label(label string, v interface{}) Option

func Name added in v1.1.5

func Name(name string) Option

func OptionLogin added in v1.1.4

func OptionLogin() Option

func RequireLogin added in v1.1.4

func RequireLogin() Option

Option to set RequireLogin

func RequirePermission added in v1.1.5

func RequirePermission(permissions ...string) Option

func Resource added in v1.1.5

func Resource(source string) Option

type OptionRegistry added in v1.1.4

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

Registry to store options for each method or route

func NewOptionRegistry added in v1.1.4

func NewOptionRegistry() *OptionRegistry

NewOptionRegistry creates a new registry

func (OptionRegistry) Get added in v1.1.4

func (o OptionRegistry) Get(method Method, pattern string) (options *HandlerOptions, ok bool)

func (OptionRegistry) GetKey added in v1.1.4

func (o OptionRegistry) GetKey(method Method, pattern string) string

func (OptionRegistry) Register added in v1.1.4

func (o OptionRegistry) Register(method Method, pattern string, options *HandlerOptions)

type RecoveryOption

type RecoveryOption func(http.Handler)

RecoveryOption provides a functional approach to define configuration for a handler; such as setting the logging whether or not to print stack traces on panic.

func PrintRecoveryStack

func PrintRecoveryStack(print bool) RecoveryOption

PrintRecoveryStack is a functional option to enable or disable printing stack traces on panic.

type RegisteredAPIHandler added in v1.1.4

type RegisteredAPIHandler struct {
	Options *HandlerOptions
	Handler func(w http.ResponseWriter, req *http.Request, ps httprouter.Params)
}

type Response

type Response struct {
	Total  int64       `json:"total,omitempty"`
	Hit    interface{} `json:"hit,omitempty"`
	Id     string      `json:"_id,omitempty"`
	Result string      `json:"result,omitempty"`
}

func CreateResponse

func CreateResponse(id string) Response

func DeleteResponse

func DeleteResponse(id string) Response

func UpdateResponse

func UpdateResponse(id string) Response

type Result

type Result struct {
	Total  int64       `json:"total"`
	Result interface{} `json:"result"`
}

Result is a general json result

type UIFilters added in v1.1.4

type UIFilters interface {
	// ApplyFilter wraps an HTTP handler with filter logic
	ApplyFilter(
		method string,
		pattern string,
		options *HandlerOptions,
		next httprouter.Handle,
	) httprouter.Handle

	// GetPriority determines execution order (lower values execute first)
	GetPriority() int
}

Directories

Path Synopsis
Package httprouter is a trie based high performance HTTP request router.
Package httprouter is a trie based high performance HTTP request router.

Jump to

Keyboard shortcuts

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