fw

package module
v0.5.9 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2024 License: MIT Imports: 45 Imported by: 14

README

fw

Documentation

Index

Constants

View Source
const (
	AfterListen = "afterListen"
)
View Source
const MIMEOctetStream = "application/octet-stream"
View Source
const Version = "v1.0.0@beta"

Variables

This section is empty.

Functions

func EqualFold

func EqualFold[S byteSeq](b, s S) bool

EqualFold tests ascii strings or bytes for equality case-insensitively

func GetMIME

func GetMIME(extension string) string

GetMIME returns the content-type of a file extension

func GetReqHeader

func GetReqHeader[V GenericType](c *Context, key string, defaultValue ...V) V

GetReqHeader returns the HTTP request header specified by filed. This function is generic and can handle differnet headers type values.

func IsObject

func IsObject(v interface{}) bool

func StatusMessage

func StatusMessage(status int) string

StatusMessage returns the correct message for the provided HTTP statuscode

func Stringify

func Stringify(v interface{}) string

func Trim

func Trim[S byteSeq](s S, cutset byte) S

Trim is the equivalent of strings/bytes.Trim

func TrimLeft

func TrimLeft[S byteSeq](s S, cutset byte) S

TrimLeft is the equivalent of strings/bytes.TrimLeft

func TrimRight

func TrimRight[S byteSeq](s S, cutset byte) S

TrimRight is the equivalent of strings/bytes.TrimRight

func UUID

func UUID() string

UUID generates an universally unique identifier (UUID)

func UUIDv4

func UUIDv4() string

UUIDv4 returns a Random (Version 4) UUID. The strength of the UUIDs is based on the strength of the crypto/rand package.

Types

type AttributeName

type AttributeName = string

type ConfigMapper added in v0.3.6

type ConfigMapper interface {
	LoadWithKey(key string, config any) error
}

ConfigMapper is the interface for config mapper which can make a struct able to load configuration

type Context

type Context struct {
	Keys map[string]any

	ErrHandler func(*Context, error)
	// contains filtered or unexported fields
}

func (*Context) Append

func (c *Context) Append(field string, values ...string)

Append the specified value to the HTTP response header field. If the header is not already set, it creates the header with the specified value.

func (*Context) Apply

func (c *Context) Apply(ctl interface{}) error

func (*Context) AsciiJSON

func (c *Context) AsciiJSON(code int, obj any)

func (*Context) ContextString

func (c *Context) ContextString() string

ContextString returns unique string representation of the ctx.

The returned value may be useful for logging.

func (*Context) Data

func (c *Context) Data(code int, contentType string, data []byte) *Context

func (*Context) DataExit added in v0.4.1

func (c *Context) DataExit(data any)

func (*Context) DataFromReader

func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string)

func (*Context) Error

func (c *Context) Error(err error)

func (*Context) ErrorExit added in v0.4.1

func (c *Context) ErrorExit(err error)

func (*Context) ErrorExitWithCode added in v0.4.1

func (c *Context) ErrorExitWithCode(code int, err error)

func (*Context) Exit added in v0.4.1

func (c *Context) Exit()

func (*Context) File

func (c *Context) File(filepath string) *Context

func (*Context) FileAttachment

func (c *Context) FileAttachment(filepath, filename string) *Context

func (*Context) Get

func (c *Context) Get(key string) (value any, exists bool)

func (*Context) GetBool

func (c *Context) GetBool(key string) (b bool)

func (*Context) GetDuration

func (c *Context) GetDuration(key string) (d time.Duration)

func (*Context) GetFastContext

func (c *Context) GetFastContext() *fasthttp.RequestCtx

TODO: 这个方法应该被取消或私有, 为了配合hasReturn

func (*Context) GetFloat64

func (c *Context) GetFloat64(key string) (f64 float64)

func (*Context) GetHeader

func (c *Context) GetHeader(key string, defaultValue ...string) string

GetHeader returns the HTTP request header specified by field. Field names are case-insensitive Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.

func (*Context) GetInt

func (c *Context) GetInt(key string) (i int)

func (*Context) GetInt64

func (c *Context) GetInt64(key string) (i64 int64)

func (*Context) GetString

func (c *Context) GetString(key string) (s string)

func (*Context) GetStringMap

func (c *Context) GetStringMap(key string) (sm map[string]any)

func (*Context) GetStringMapString

func (c *Context) GetStringMapString(key string) (sms map[string]string)

func (*Context) GetStringMapStringSlice

func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string)

func (*Context) GetStringSlice

func (c *Context) GetStringSlice(key string) (ss []string)

func (*Context) GetTime

func (c *Context) GetTime(key string) (t time.Time)

func (*Context) GetUint

func (c *Context) GetUint(key string) (ui uint)

func (*Context) GetUint64

func (c *Context) GetUint64(key string) (ui64 uint64)

func (*Context) HTML

func (c *Context) HTML(code int, name string, obj any)

func (*Context) HTMLPure added in v0.1.1

func (c *Context) HTMLPure(code int, content string, obj any) *Context

func (*Context) Host added in v0.3.4

func (c *Context) Host() string

func (*Context) Injector

func (c *Context) Injector() inject.Injector

func (*Context) Invoke added in v0.2.1

func (c *Context) Invoke(i interface{}) ([]reflect.Value, error)

func (*Context) IsFromLocal

func (c *Context) IsFromLocal() bool

IsFromLocal will return true if request came from local.

func (*Context) JSON

func (c *Context) JSON(code int, obj any)

func (*Context) JSONP

func (c *Context) JSONP(data any, callback ...string)

func (*Context) Location

func (c *Context) Location(path string) *Context

Location sets the response Location HTTP header to the specified path parameter.

func (*Context) Map

func (c *Context) Map(i ...interface{}) inject.TypeMapper

func (*Context) MapTo

func (c *Context) MapTo(i interface{}, j interface{}) inject.TypeMapper

func (*Context) Method

func (c *Context) Method() string

func (*Context) MultipartForm added in v0.3.4

func (c *Context) MultipartForm() (*multipart.Form, error)

func (*Context) MustGet

func (c *Context) MustGet(key string) any

func (*Context) Param

func (c *Context) Param(key string) string

func (*Context) ParamErrorExit added in v0.4.1

func (c *Context) ParamErrorExit(key string, msg string)

func (*Context) PostArgs added in v0.3.4

func (c *Context) PostArgs() *fasthttp.Args

func (*Context) PostBody added in v0.3.4

func (c *Context) PostBody() []byte

func (*Context) Protocol

func (c *Context) Protocol() string

Protocol returns the HTTP protocol of request: HTTP/1.1 and HTTP/2.

func (*Context) Provide

func (c *Context) Provide(i interface{}) error

func (*Context) PureJSON

func (c *Context) PureJSON(code int, obj any)

func (*Context) QueryArgs added in v0.3.4

func (c *Context) QueryArgs() *fasthttp.Args

func (*Context) Redirect

func (c *Context) Redirect(code int, location string)

func (*Context) RemoteIP

func (c *Context) RemoteIP() string

func (*Context) RequestURI added in v0.3.4

func (c *Context) RequestURI() string

func (*Context) ResetBody added in v0.3.4

func (c *Context) ResetBody() *Context

func (*Context) ResponseBody added in v0.3.4

func (c *Context) ResponseBody() []byte

func (*Context) SaveUploadFile added in v0.1.1

func (c *Context) SaveUploadFile(file *multipart.FileHeader, dst string) error

func (*Context) SendStatus

func (c *Context) SendStatus(status int)

SendStatus sets the HTTP status code and if the response body is empty, it sets the correct status message in the body.

func (*Context) SendStream

func (c *Context) SendStream(stream io.Reader, size ...int) error

SendStream sets response body stream and optional body size.

func (*Context) ServeFS added in v0.3.4

func (c *Context) ServeFS(fs fs.FS, path string) *Context

func (*Context) Set

func (c *Context) Set(key string, value any)

func (*Context) SetContentType added in v0.3.4

func (c *Context) SetContentType(value string) *Context

func (*Context) SetHeader

func (c *Context) SetHeader(key, val string) *Context

SetHeader sets the response's HTTP header field to the specified key, value.

func (*Context) Status

func (c *Context) Status(code int)

func (*Context) Stream

func (c *Context) Stream(step func(w *bufio.Writer))

Stream sends a streaming response and returns a boolean indicates "Is client disconnected in middle of stream"

func (*Context) String

func (c *Context) String(code int, format string, values ...any)

func (*Context) SuccessExit added in v0.4.1

func (c *Context) SuccessExit()

func (*Context) Type

func (c *Context) Type(extension string, charset ...string) *Context

Type sets the Content-Type HTTP header to the MIME type specified by the file extension.

func (*Context) UserAgent added in v0.3.4

func (c *Context) UserAgent() string

func (*Context) Vary

func (c *Context) Vary(fields ...string)

Vary adds the given header field to the Vary response header. This will append the header, if not already listed, otherwise leaves it listed in the current location.

func (*Context) VisitPostArgs added in v0.3.4

func (c *Context) VisitPostArgs(callback func(key string, value string))

func (*Context) VisitQueryArgs added in v0.3.4

func (c *Context) VisitQueryArgs(callback func(key string, value string))

func (*Context) Write

func (c *Context) Write(p []byte) (int, error)

Write appends p into response body.

func (*Context) WriteString

func (c *Context) WriteString(s string) *Context

WriteString appends s to response body.

func (*Context) Writef

func (c *Context) Writef(f string, a ...any) (int, error)

Writef appends `f` & `a` into response body writer.

func (*Context) XHR

func (c *Context) XHR() bool

XHR returns a Boolean property, that is true, if the request's X-Requested-With header field is XMLHttpRequest, indicating that the request was issued by a client library (such as jQuery).

func (*Context) XML

func (c *Context) XML(code int, obj any)

type Entry

type Entry struct {
	*logrus.Entry
}

func (*Entry) Debug

func (entry *Entry) Debug(args ...interface{})

func (*Entry) Error

func (entry *Entry) Error(args ...interface{})

func (*Entry) Fatal

func (entry *Entry) Fatal(args ...interface{})

func (*Entry) Info

func (entry *Entry) Info(args ...interface{})

func (*Entry) Panic

func (entry *Entry) Panic(args ...interface{})

func (*Entry) Trace

func (entry *Entry) Trace(args ...interface{})

func (*Entry) Warn

func (entry *Entry) Warn(args ...interface{})

type Formatter

type Formatter struct {
	PrettyPrint bool
	Colorize    bool
}

func Console

func Console() *Formatter

func File added in v0.2.7

func File() *Formatter

func (*Formatter) Format

func (f *Formatter) Format(entry *logrus.Entry) ([]byte, error)

type GenericType

type GenericType interface {
	GenericTypeInteger | GenericTypeFloat | bool | string | []byte
}

type GenericTypeFloat

type GenericTypeFloat interface {
	float32 | float64
}

type GenericTypeInteger

type GenericTypeInteger interface {
	GenericTypeIntegerSigned | GenericTypeIntegerUnsigned
}

type GenericTypeIntegerSigned

type GenericTypeIntegerSigned interface {
	int | int8 | int16 | int32 | int64
}

type GenericTypeIntegerUnsigned

type GenericTypeIntegerUnsigned interface {
	uint | uint8 | uint16 | uint32 | uint64
}

type H

type H map[string]any

func (H) MarshalXML

func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error

type HandlerFunc

type HandlerFunc = func(*Context)

type HookHandler

type HookHandler interface {
	HandleServerInfo(si []string)
	HandleStructs(ctl *astp.Element)

	Print(slot string)
}

type IConfig added in v0.3.0

type IConfig interface {
	LoadConfig(key string, config any)
	// contains filtered or unexported methods
}

type IController added in v0.3.2

type IController interface {
	// Init will be called after the controller is created and the service will be passed to the controller
	// via the provider. The controller should use the provider to get the service instance,
	Init(provider IProvider)
}

IController is the interface for controller a controller which implements this interface will have an Init method to provide something (e.g. database orm instance)

type IControllerConfig added in v0.3.8

type IControllerConfig interface {
	InitConfig(config ConfigMapper)
}

IControllerConfig is the interface for controller a controller which implements this interface will have an InitConfig method to load configuration

type IInitOnce added in v0.3.0

type IInitOnce interface {
	DoInitOnce()
}

IInitOnce is an interface that will be called only once

type IMiddleware

type IMiddleware interface {
	IMiddlewareBase
	IConfig
	IInitOnce
	IReg
	IProvider
}

IMiddleware interface of middleware

type IMiddlewareBase added in v0.3.0

type IMiddlewareBase interface {
	// Name returns the middleware's name
	Name() string
	// Attribute returns the middleware's Attribute just like Websocket so that you can use it like // @Websocket
	Attribute() AttributeName
	// GetSlot returns slot type
	GetSlot() SlotType
}

type IMiddlewareCtl

type IMiddlewareCtl interface {
	IMiddlewareMethod
	Router(ctx *MiddlewareContext) []*RouteItem
}

type IMiddlewareGlobal

type IMiddlewareGlobal interface {
	IMiddlewareCtl
}

type IMiddlewareMethod

type IMiddlewareMethod interface {
	IMiddleware
	Execute(ctx *MiddlewareContext) HandlerFunc
}

type IPlugin added in v0.5.0

type IPlugin interface {
	InitPlugin(s *Server)
	HandleServerInfo(si []string)
	HandleStructs(ctl *astp.Element)
	Print(slot string)
}

type IProvider added in v0.5.4

type IProvider interface {
	inject.Provider
}

type IReg added in v0.3.0

type IReg interface {
	// contains filtered or unexported methods
}

type IService added in v0.4.1

type IService interface {

	// Init will be called after the service is created and the provider and config will be passed to the service
	// via the provider. The service should use the provider to get the service instance,
	Init(provider IProvider)
}

IService is the interface for service a service which implements this interface will have an Init method to provide something (e.g. database orm instance)

type IServiceConfig added in v0.4.1

type IServiceConfig interface {
	InitConfig(config ConfigMapper)
}

IServiceConfig is the interface for service a service which implements this interface will have an InitConfig method to load configuration

type JO

type JO map[string]interface{}

type LogFileHook

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

func NewFileHook

func NewFileHook(output interface{}, formatter logrus.Formatter) *LogFileHook

func (*LogFileHook) Fire

func (hook *LogFileHook) Fire(entry *logrus.Entry) error

func (*LogFileHook) Levels

func (hook *LogFileHook) Levels() []logrus.Level

func (*LogFileHook) SetDefaultPath

func (hook *LogFileHook) SetDefaultPath(defaultPath string)

func (*LogFileHook) SetDefaultWriter

func (hook *LogFileHook) SetDefaultWriter(defaultWriter io.Writer)

func (*LogFileHook) SetFormatter

func (hook *LogFileHook) SetFormatter(formatter logrus.Formatter)

type LoggerOption added in v0.2.4

type LoggerOption struct {
	LoggerLevel       int    `yaml:"loggerLevel" default:"4"` //0-6 0: Panic 6: Trace
	SeparateLevelFile bool   `yaml:"separateLevelFile" default:"false"`
	LogDir            string `yaml:"logDir" default:"log"`
	RotateFile        bool   `yaml:"rotate" default:"true"`
	MaxSize           int    `yaml:"maxSize" default:"5"`
	MaxAge            int    `yaml:"maxAge" default:"28"`
	MaxBackups        int    `yaml:"maxBackups" default:"3"`
	Compress          bool   `yaml:"compress" default:"false"`
	LocalTime         bool   `yaml:"localTime" default:"true"`
}

type Middleware

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

func NewMiddleware

func NewMiddleware(name string, slot string, attr string) *Middleware

NewMiddleware creates a new Middleware instance

func (*Middleware) Attribute

func (m *Middleware) Attribute() AttributeName

func (*Middleware) DoInitOnce added in v0.3.0

func (m *Middleware) DoInitOnce()

func (*Middleware) GetSlot

func (m *Middleware) GetSlot() SlotType

func (*Middleware) LoadConfig added in v0.3.0

func (m *Middleware) LoadConfig(key string, config any)

LoadConfig loads the configuration with the specified key and value into the Middleware's config.

Parameters: - key: the key used to identify the configuration. - config: the configuration value to be loaded.

Return type: None.

func (*Middleware) Name

func (m *Middleware) Name() string

func (*Middleware) Provide added in v0.4.1

func (m *Middleware) Provide(i interface{}) error

type MiddlewareContainer

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

MiddlewareContainer stores middlewares global middlewares will be stored with its Name as key

func NewMiddlewareContainer

func NewMiddlewareContainer() *MiddlewareContainer

func (*MiddlewareContainer) GetByAttribute

func (m *MiddlewareContainer) GetByAttribute(slot string, attribute string) (IMiddleware, bool)

GetByAttribute returns middleware with specified slot and attr.

func (*MiddlewareContainer) GetByAttributeCtl

func (m *MiddlewareContainer) GetByAttributeCtl(attribute string) (IMiddlewareCtl, bool)

GetByAttributeCtl find controller middleware(IMiddlewareCtl) with attribute name

func (*MiddlewareContainer) GetByAttributeMethod

func (m *MiddlewareContainer) GetByAttributeMethod(attribute string) (IMiddlewareMethod, bool)

GetByAttributeMethod find method middleware(IMiddlewareMethod) with attribute name

func (*MiddlewareContainer) GetGlobal

func (m *MiddlewareContainer) GetGlobal(f func(middleware IMiddlewareGlobal) bool) bool

GetGlobal iterate global middlewares stop at `f` returns true

func (*MiddlewareContainer) Reg

func (m *MiddlewareContainer) Reg(middleware IMiddleware)

Reg will store middleware to specified map according to its slot

func (*MiddlewareContainer) VisitAll

func (m *MiddlewareContainer) VisitAll(slot string, f func(middleware IMiddleware) bool) bool

VisitAll visit all middlewares with the specified slot if f returns true, the loop will terminate

type MiddlewareContext added in v0.3.0

type MiddlewareContext struct {
	ControllerName string
	MethodName     string
	Location       SlotType

	Ignored bool
	Next    HandlerFunc
	// contains filtered or unexported fields
}

MiddlewareContext represents the context in which a middleware is executed.

func (*MiddlewareContext) DelParam added in v0.3.0

func (m *MiddlewareContext) DelParam(key string)

DelParam deletes the value associated with key from middleware context's parameters.

func (*MiddlewareContext) GetParam added in v0.3.0

func (m *MiddlewareContext) GetParam(key string) string

GetParam returns the value associated with key from middleware context's parameters.

If the key is present in the map, the value (string) is returned. If the key is not present in the map, an empty string is returned.

func (*MiddlewareContext) GetRValue added in v0.3.0

func (m *MiddlewareContext) GetRValue() reflect.Value

func (*MiddlewareContext) GetRawParams added in v0.5.4

func (m *MiddlewareContext) GetRawParams() string

GetRawParams returns the raw parameters of the middleware context.

func (*MiddlewareContext) SetRValue added in v0.3.0

func (m *MiddlewareContext) SetRValue(v reflect.Value)

func (*MiddlewareContext) VisitParams added in v0.3.0

func (m *MiddlewareContext) VisitParams(f func(key string, value []string))

VisitParams calls the given function f for each key/value pair in middleware context's parameters.

f is called with the key and value of each parameter. The value is a slice of strings.

type MiddlewareCtl

type MiddlewareCtl struct {
	*MiddlewareMethod
}

func NewMiddlewareCtl

func NewMiddlewareCtl(name string, attr string) *MiddlewareCtl

func NewMiddlewareCtlForGlobal added in v0.3.0

func NewMiddlewareCtlForGlobal(name string) *MiddlewareCtl

func (*MiddlewareCtl) Execute added in v0.3.0

func (m *MiddlewareCtl) Execute(ctx *MiddlewareContext) HandlerFunc

func (*MiddlewareCtl) Router added in v0.3.0

func (m *MiddlewareCtl) Router(ctx *MiddlewareContext) []*RouteItem

type MiddlewareGlobal

type MiddlewareGlobal struct {
	*MiddlewareCtl
}

func NewMiddlewareGlobal

func NewMiddlewareGlobal(name string) *MiddlewareGlobal

type MiddlewareMethod

type MiddlewareMethod struct {
	*Middleware
}

func NewMiddlewareMethod

func NewMiddlewareMethod(name string, attr string) *MiddlewareMethod

func NewMiddlewareMethodForCtl added in v0.2.1

func NewMiddlewareMethodForCtl(name string, attr string) *MiddlewareMethod

func NewMiddlewareMethodForGlobal added in v0.3.0

func NewMiddlewareMethodForGlobal(name string) *MiddlewareMethod

type PathMap

type PathMap map[logrus.Level]string

type RootFields

type RootFields struct {
	Timestamp string
	Func      string
	Level     logrus.Level
	Fields    interface{}
}

type RouteItem

type RouteItem struct {
	Method           string         // HTTP METHOD
	Path             string         // route path
	IsHide           bool           // if set true, this route will not show in route table
	H                HandlerFunc    // handler for this route
	Middleware       IMiddlewareCtl // just refer to middleware itself
	OverrideBasePath bool           // override base path
}

RouteItem is a struct that holds information about a route

a Middleware can return a []*RouteItem which will be registered to server

type Server

type Server struct {
	inject.Injector
	// contains filtered or unexported fields
}

func New

func New(key ...string) *Server

func (*Server) AddPlugin added in v0.5.0

func (s *Server) AddPlugin(plugin IPlugin)

func (*Server) BasePath added in v0.4.4

func (s *Server) BasePath() string

func (*Server) CanAccessByLan added in v0.3.9

func (s *Server) CanAccessByLan() bool

func (*Server) ListenAddr added in v0.4.4

func (s *Server) ListenAddr() string

func (*Server) Port added in v0.4.4

func (s *Server) Port() int

func (*Server) RegisterRoute

func (s *Server) RegisterRoute(controller any)

func (*Server) RegisterRoutes

func (s *Server) RegisterRoutes(controller ...any)

func (*Server) Run

func (s *Server) Run() chan bool

func (*Server) Schema added in v0.4.4

func (s *Server) Schema() string

func (*Server) Start added in v0.3.0

func (s *Server) Start()

func (*Server) Use

func (s *Server) Use(middleware ...IMiddleware)

Use register middleware to server. you can only use the @'Attribute' after register a middleware

func (*Server) UseMapper added in v0.3.2

func (s *Server) UseMapper(mapper ...ServiceMapper)

func (*Server) UseService added in v0.4.1

func (s *Server) UseService(service ...IService)

func (*Server) UseServiceWithConfig added in v0.4.1

func (s *Server) UseServiceWithConfig(service ...IServiceConfig)

type ServerOption added in v0.2.4

type ServerOption struct {
	IntranetIP            string
	Dev                   bool         `yaml:"dev" default:"true"`
	Debug                 bool         `yaml:"debug" default:"true"`
	NoColor               bool         `yaml:"nocolor" default:"false"`
	BasePath              string       `yaml:"basePath" default:"/"`
	Listen                string       `yaml:"listen" default:"127.0.0.1"` //监听地址
	Title                 string       `yaml:"title" default:"fw api"`
	Name                  string       `yaml:"name" default:"fw"` //server_token
	ShowRequestTimeHeader bool         `yaml:"showRequestTimeHeader,omitempty" default:"true"`
	RequestTimeHeader     string       `yaml:"requestTimeHeader,omitempty" default:"Request-Time"`
	Port                  int          `yaml:"port" default:"2024"`
	AstFile               string       `yaml:"astFile" default:"gen.json"` //ast json file generated by github.com/linxlib/astp. default is gen.json
	Logger                LoggerOption `yaml:"logger"`
}

type ServiceMapper added in v0.3.2

type ServiceMapper interface {
	// Init do some initializations for service
	// system will Map the result into inject container when no error
	// will panic when error
	Init(config ConfigMapper) (any, error)
}

ServiceMapper is the interface for service mapper do some initializations for service and then inject something into the container

type SlotType

type SlotType = string
const (
	SlotGlobal     SlotType = "global"
	SlotController SlotType = "controller"
	SlotMethod     SlotType = "method"
)

type WriterMap

type WriterMap map[logrus.Level]io.Writer

Directories

Path Synopsis
cmd module
example module

Jump to

Keyboard shortcuts

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