Documentation
¶
Index ¶
- func Debug(msg string, args ...any)
- func Error(msg string, args ...any)
- func Fatal(msg string, args ...any)
- func GetBuffer() []byte
- func Info(msg string, args ...any)
- func ReleaseBuffer(buf []byte)
- func ReleaseContext(ctx *Context)
- func SetDefaultLogger(log Logger)
- func SetupLogRotation(config LogRotateConfig) error
- func Warn(msg string, args ...any)
- type AdaptiveCache
- func (c *AdaptiveCache) Clear()
- func (c *AdaptiveCache) Close()
- func (c *AdaptiveCache) Delete(key string)
- func (c *AdaptiveCache) Disable()
- func (c *AdaptiveCache) Enable()
- func (c *AdaptiveCache) Get(key string) (interface{}, bool)
- func (c *AdaptiveCache) Set(key string, value interface{}, responseTime time.Duration)
- func (c *AdaptiveCache) Stats() (hits, misses, evictions uint64, size, capacity int64)
- type AdaptiveCacheConfig
- type AlertCallback
- type AnyValue
- func (av AnyValue) AsBytes() ([]byte, error)
- func (av AnyValue) AsFloat32() (float32, error)
- func (av AnyValue) AsFloat64() (float64, error)
- func (av AnyValue) AsInt() (int, error)
- func (av AnyValue) AsInt16() (int16, error)
- func (av AnyValue) AsInt32() (int32, error)
- func (av AnyValue) AsInt64() (int64, error)
- func (av AnyValue) AsInt8() (int8, error)
- func (av AnyValue) AsString() (string, error)
- func (av AnyValue) AsUint() (uint, error)
- func (av AnyValue) AsUint16() (uint16, error)
- func (av AnyValue) AsUint32() (uint32, error)
- func (av AnyValue) AsUint64() (uint64, error)
- func (av AnyValue) AsUint8() (uint8, error)
- func (av AnyValue) Bool() (bool, error)
- func (av AnyValue) BoolOrDefault(def bool) bool
- func (av AnyValue) Bytes() ([]byte, error)
- func (av AnyValue) BytesOrDefault(def []byte) []byte
- func (av AnyValue) Float32() (float32, error)
- func (av AnyValue) Float32OrDefault(def float32) float32
- func (av AnyValue) Float64() (float64, error)
- func (av AnyValue) Float64OrDefault(def float64) float64
- func (av AnyValue) Int() (int, error)
- func (av AnyValue) Int16() (int16, error)
- func (av AnyValue) Int16OrDefault(def int16) int16
- func (av AnyValue) Int32() (int32, error)
- func (av AnyValue) Int32OrDefault(def int32) int32
- func (av AnyValue) Int64() (int64, error)
- func (av AnyValue) Int64OrDefault(def int64) int64
- func (av AnyValue) Int8() (int8, error)
- func (av AnyValue) Int8OrDefault(def int8) int8
- func (av AnyValue) IntOrDefault(def int) int
- func (av AnyValue) JSONScan(val any) error
- func (av AnyValue) String() (string, error)
- func (av AnyValue) StringOrDefault(def string) string
- func (av AnyValue) Uint() (uint, error)
- func (av AnyValue) Uint16() (uint16, error)
- func (av AnyValue) Uint16OrDefault(def uint16) uint16
- func (av AnyValue) Uint32() (uint32, error)
- func (av AnyValue) Uint32OrDefault(def uint32) uint32
- func (av AnyValue) Uint64() (uint64, error)
- func (av AnyValue) Uint64OrDefault(def uint64) uint64
- func (av AnyValue) Uint8() (uint8, error)
- func (av AnyValue) Uint8OrDefault(def uint8) uint8
- func (av AnyValue) UintOrDefault(def uint) uint
- type Context
- func (c *Context) AbortWithStatus(code int)
- func (c *Context) BindJSON(val any) error
- func (c *Context) BindJSONOpt(val any, useNumber bool, disableUnknown bool) error
- func (c *Context) Cancel()
- func (c *Context) ClientIP() string
- func (c *Context) Context() context.Context
- func (c *Context) Deadline() (time.Time, bool)
- func (c *Context) Done() <-chan struct{}
- func (c *Context) Err() error
- func (c *Context) FormValue(key string) AnyValue
- func (c *Context) Get(key string) (value any, exists bool)
- func (c *Context) GetBool(key string) (b bool)
- func (c *Context) GetDuration(key string) (d time.Duration)
- func (c *Context) GetFloat64(key string) (f64 float64)
- func (c *Context) GetInt(key string) (i int)
- func (c *Context) GetInt64(key string) (i64 int64)
- func (c *Context) GetString(key string) (s string)
- func (c *Context) GetStringMap(key string) (sm map[string]any)
- func (c *Context) GetStringMapString(key string) (sms map[string]string)
- func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string)
- func (c *Context) GetStringSlice(key string) (ss []string)
- func (c *Context) GetTime(key string) (t time.Time)
- func (c *Context) GetUint(key string) (ui uint)
- func (c *Context) GetUint64(key string) (ui64 uint64)
- func (c *Context) Header(key, value string)
- func (c *Context) MustGet(key string) any
- func (c *Context) PathValue(key string) AnyValue
- func (c *Context) QueryValue(key string) AnyValue
- func (c *Context) RemoteIP() string
- func (c *Context) Render(templateName string, data any) error
- func (c *Context) RequestID() string
- func (c *Context) RespondSuccess(val any) error
- func (c *Context) RespondWithJSON(status int, val any) error
- func (c *Context) RespondWithJSONBuffer(status int, val any) error
- func (c *Context) Set(key string, value any)
- func (c *Context) SetCookie(ck *http.Cookie)
- func (c *Context) Value(key any) any
- func (c *Context) WithTimeout(timeout time.Duration)
- type FileDownloader
- type FileUploader
- type GoTemplateEngine
- func (g *GoTemplateEngine) LoadFromFS(fs fs.FS, patterns ...string) error
- func (g *GoTemplateEngine) LoadFromFiles(filenames ...string) error
- func (g *GoTemplateEngine) LoadFromGlob(pattern string) error
- func (g *GoTemplateEngine) Render(ctx context.Context, templateName string, data any) ([]byte, error)
- type HTTP3Config
- type HTTP3Server
- type HTTPServer
- func (s *HTTPServer) CONNECT(path string, handleFunc HandleFunc, ms ...Middleware)
- func (r *HTTPServer) CacheStats() (hits, misses uint64, size int)
- func (s *HTTPServer) DELETE(path string, handleFunc HandleFunc, ms ...Middleware)
- func (r *HTTPServer) DisableCache()
- func (s *HTTPServer) DisableRouteStats()
- func (r *HTTPServer) DisableStats()
- func (r *HTTPServer) EnableCache(maxSize int)
- func (s *HTTPServer) EnableRouteStats()
- func (r *HTTPServer) EnableStats()
- func (s *HTTPServer) GET(path string, handleFunc HandleFunc, ms ...Middleware)
- func (s *HTTPServer) GetAllRouteStats() map[string]map[string]interface{}
- func (s *HTTPServer) GetRouteStats(route string) (map[string]interface{}, bool)
- func (r *HTTPServer) Group(prefix string, ms ...Middleware) *routerGroup
- func (s *HTTPServer) HEAD(path string, handleFunc HandleFunc, ms ...Middleware)
- func (s *HTTPServer) OPTIONS(path string, handleFunc HandleFunc, ms ...Middleware)
- func (s *HTTPServer) PATCH(path string, handleFunc HandleFunc, ms ...Middleware)
- func (s *HTTPServer) POST(path string, handleFunc HandleFunc, ms ...Middleware)
- func (s *HTTPServer) PUT(path string, handleFunc HandleFunc, ms ...Middleware)
- func (s *HTTPServer) ResetRouteStats()
- func (s *HTTPServer) ServeHTTP(writer http.ResponseWriter, request *http.Request)
- func (s *HTTPServer) Shutdown(ctx context.Context) error
- func (s *HTTPServer) Start(addr string) error
- func (s *HTTPServer) StartHTTP3(addr, certFile, keyFile string) error
- func (s *HTTPServer) StartTLS(addr, certFile, keyFile string) error
- func (s *HTTPServer) Use(mdls ...Middleware)
- func (s *HTTPServer) UseForAll(path string, mdls ...Middleware)
- func (s *HTTPServer) UseRoute(method string, path string, mils ...Middleware)
- type HTTPServerOption
- type HandleFunc
- type LogLevel
- type LogRotateConfig
- type LogRotator
- type Logger
- type MemStats
- type MemoryMonitor
- func (m *MemoryMonitor) AddAlertCallback(callback AlertCallback)
- func (m *MemoryMonitor) ForceGC()
- func (m *MemoryMonitor) GetCurrentStats() MemStats
- func (m *MemoryMonitor) GetMemoryUsageReport() map[string]interface{}
- func (m *MemoryMonitor) GetSamples() []MemStats
- func (m *MemoryMonitor) SetAlertThreshold(threshold float64)
- func (m *MemoryMonitor) Start()
- func (m *MemoryMonitor) Stop()
- type Middleware
- type PathTrie
- type Server
- type ServerConfig
- type StaticResourceHandler
- type StaticResourceHandlerOption
- type StdLogger
- func (l *StdLogger) Debug(msg string, args ...any)
- func (l *StdLogger) Error(msg string, args ...any)
- func (l *StdLogger) Fatalln(msg string, args ...any)
- func (l *StdLogger) GetLevel() LogLevel
- func (l *StdLogger) Info(msg string, args ...any)
- func (l *StdLogger) SetLevel(level LogLevel)
- func (l *StdLogger) SetOutput(w io.Writer)
- func (l *StdLogger) Warn(msg string, args ...any)
- func (l *StdLogger) WithField(key string, value any) Logger
- type TemplateEngine
- type ZeroCopyResponse
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ReleaseContext ¶ added in v0.1.21
func ReleaseContext(ctx *Context)
ReleaseContext 将Context归还到对象池
func SetDefaultLogger ¶ added in v0.0.13
func SetDefaultLogger(log Logger)
SetDefaultLogger is a function that allows for the configuration of the application's default logging behavior by setting the provided logger as the new default logger.
Parameters:
log Logger: This parameter is an implementation of the Logger interface.
It represents the logger instance that the application should
use as its new default logger. This logger will be used for
all logging activities across the application, enabling a
consistent logging approach.
Purpose: The primary purpose of SetDefaultLogger is to provide a mechanism for changing the logging implementation used by an application at runtime. This is particularly useful in scenarios where the logging requirements change based on the environment the application is running in (e.g., development, staging, production) or when integrating with different third-party logging services.
Usage: To use SetDefaultLogger, an instance of a Logger implementation needs to be passed to it. This can be a custom logger tailored to the application's specific needs or an instance from a third-party logging library that adheres to the Logger interface. Once SetDefaultLogger is called with the new logger, all subsequent calls to the defaultLogger variable throughout the application will use this new logger instance, thereby affecting how logs are recorded and stored.
Example: Suppose you have an application that uses a basic logging mechanism by default but requires integration with a more sophisticated logging system (like logrus or zap) for production environments. You can initialize the desired logger and pass it to SetDefaultLogger during the application's initialization phase. This ensures that all logging throughout the application uses the newly specified logger.
Note: It is important to call SetDefaultLogger before any logging activity occurs to ensure that logs are consistently handled by the chosen logger. Failure to do so may result in some logs being handled by a different logger than intended, leading to inconsistency in log handling and potential loss of log data.
func SetupLogRotation ¶ added in v0.1.19
func SetupLogRotation(config LogRotateConfig) error
SetupLogRotation 设置日志轮转,这里只是示例,未实现具体逻辑
Types ¶
type AdaptiveCache ¶ added in v0.1.27
type AdaptiveCache struct {
// contains filtered or unexported fields
}
AdaptiveCache 是一个自适应的路由缓存结构 该缓存会根据路由的访问频率和响应时间动态调整缓存空间分配
func NewAdaptiveCache ¶ added in v0.1.27
func NewAdaptiveCache(config AdaptiveCacheConfig) *AdaptiveCache
NewAdaptiveCache 创建一个新的自适应缓存
func (*AdaptiveCache) Delete ¶ added in v0.1.27
func (c *AdaptiveCache) Delete(key string)
Delete 从缓存删除值
func (*AdaptiveCache) Get ¶ added in v0.1.27
func (c *AdaptiveCache) Get(key string) (interface{}, bool)
Get 从缓存获取值
func (*AdaptiveCache) Set ¶ added in v0.1.27
func (c *AdaptiveCache) Set(key string, value interface{}, responseTime time.Duration)
Set 将值设置到缓存
func (*AdaptiveCache) Stats ¶ added in v0.1.27
func (c *AdaptiveCache) Stats() (hits, misses, evictions uint64, size, capacity int64)
Stats 返回缓存统计信息
type AdaptiveCacheConfig ¶ added in v0.1.27
type AdaptiveCacheConfig struct {
MaxSize int64 // 最大缓存条目数量
CleanupInterval time.Duration // 清理间隔时间
MinAccessCount int64 // 最小访问次数,低于此值会被优先考虑淘汰
AccessTimeWeight float64 // 访问时间权重(0-1)
FrequencyWeight float64 // 频率权重(0-1)
ResponseTimeWeight float64 // 响应时间权重(0-1)
AdaptiveMode bool // 是否启用自适应模式
}
AdaptiveCacheConfig 定义缓存的配置选项
type AlertCallback ¶ added in v0.1.27
AlertCallback 是内存告警回调函数类型
type AnyValue ¶ added in v0.1.10
type AnyValue struct {
Val any // Val represents the value of any type that this struct holds
Err error // Err represents an optional error associated with the value
}
AnyValue provides a structure to store any value along with an optional error
func (AnyValue) AsBytes ¶ added in v0.1.10
AsBytes tries to interpret the stored value as a byte slice ([]byte), handling string conversion to []byte if necessary. If av.Err is not nil, the function returns the error immediately. It uses a type switch to differentiate between []byte and string types. If the type is string, it converts the string to a byte slice ([]byte).
Parameters: None Returns: - []byte: The byte slice value after conversion. - error: An optional error if something went wrong during type assertion or conversion, or if av.Err is not nil.
func (AnyValue) AsFloat32 ¶ added in v0.1.10
AsFloat32 tries to interpret the stored value as a float32, handling string conversion to float32 if necessary. If av.Err is not nil, the function returns the error immediately. It uses a type switch to differentiate between float32 and string types. If the type is string, it tries to parse the string to a float32 using strconv.ParseFloat. If both assertions fail, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - float32: The float32 value after conversion. - error: An optional error if something went wrong during type assertion or parsing, or if av.Err is not nil.
func (AnyValue) AsFloat64 ¶ added in v0.1.10
AsFloat64 tries to interpret the stored value as a float64, handling string conversion to float64 if necessary. If av.Err is not nil, the function returns the error immediately. It uses a type switch to differentiate between float64 and string types. If the type is string, it tries to parse the string to a float64 using strconv.ParseFloat. If both assertions fail, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - float64: The float64 value after conversion. - error: An optional error if something went wrong during type assertion or parsing, or if av.Err is not nil.
func (AnyValue) AsInt ¶ added in v0.1.10
AsInt tries to interpret the stored value as an int, handling string conversion to int if necessary. If av.Err is not nil, the function returns the error immediately. It uses type switch to differentiate between int and string types. If the type is string, it tries to parse the string to an int. If both assertions fail, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - int: The integer value after conversion - error: An optional error if something went wrong during type assertion or parsing, or if av.Err is not nil
func (AnyValue) AsInt16 ¶ added in v0.1.10
AsInt16 tries to interpret the stored value as an int16, handling string conversion to int16 if necessary. If av.Err is not nil, the function returns the error immediately. It uses a type switch to differentiate between int16 and string types. If the type is string, it tries to parse the string to an int16. If both assertions fail, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - int16: The int16 value after conversion. - error: An optional error if something went wrong during type assertion or parsing, or if av.Err is not nil.
func (AnyValue) AsInt32 ¶ added in v0.1.10
AsInt32 tries to interpret the stored value as an int32, handling string conversion to int32 if necessary. If av.Err is not nil, the function returns the error immediately. It uses a type switch to differentiate between int32 and string types. If the type is string, it tries to parse the string to an int32. If both assertions fail, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - int32: The int32 value after conversion. - error: An optional error if something went wrong during type assertion or parsing, or if av.Err is not nil.
func (AnyValue) AsInt64 ¶ added in v0.1.10
AsInt64 tries to interpret the stored value as an int64, handling string conversion to int64 if necessary. If av.Err is not nil, the function returns the error immediately. It uses a type switch to differentiate between int64 and string types. If the type is string, it tries to parse the string to an int64. If both assertions fail, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - int64: The int64 value after conversion. - error: An optional error if something went wrong during type assertion or parsing, or if av.Err is not nil.
func (AnyValue) AsInt8 ¶ added in v0.1.10
AsInt8 tries to interpret the stored value as an int8, handling string conversion to int8 if necessary. If av.Err is not nil, the function returns the error immediately. It uses type switch to differentiate between int8 and string types. If the type is string, it tries to parse the string to an int8. If both assertions fail, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - int8: The int8 value after conversion - error: An optional error if something went wrong during type assertion or parsing, or if av.Err is not nil
func (AnyValue) AsString ¶ added in v0.1.10
AsString tries to convert various numeric and slice types to a string representation. If av.Err is not nil, the function returns the error immediately. It uses reflection to handle different types such as uint, int, float32, float64, and byte slices ([]byte).
Parameters: None Returns: - string: The string value after conversion. - error: An optional error if something went wrong during type assertion or conversion, or if av.Err is not nil.
func (AnyValue) AsUint ¶ added in v0.1.10
AsUint tries to interpret the stored value as a uint, handling string conversion to uint if necessary. If av.Err is not nil, the function returns the error immediately. It uses type switch to differentiate between uint and string types. If the type is string, it tries to parse the string to a uint. If both assertions fail, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - uint: The unsigned integer value after conversion - error: An optional error if something went wrong during type assertion or parsing, or if av.Err is not nil
func (AnyValue) AsUint16 ¶ added in v0.1.10
AsUint16 tries to interpret the stored value as a uint16, handling string conversion to uint16 if necessary. If av.Err is not nil, the function returns the error immediately. It uses a type switch to differentiate between uint16 and string types. If the type is string, it tries to parse the string to a uint16. If both assertions fail, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - uint16: The uint16 value after conversion. - error: An optional error if something went wrong during type assertion or parsing, or if av.Err is not nil.
func (AnyValue) AsUint32 ¶ added in v0.1.10
AsUint32 tries to interpret the stored value as a uint32, handling string conversion to uint32 if necessary. If av.Err is not nil, the function returns the error immediately. It uses a type switch to differentiate between uint32 and string types. If the type is string, it tries to parse the string to a uint32. If both assertions fail, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - uint32: The uint32 value after conversion. - error: An optional error if something went wrong during type assertion or parsing, or if av.Err is not nil.
func (AnyValue) AsUint64 ¶ added in v0.1.10
AsUint64 tries to interpret the stored value as a uint64, handling string conversion to uint64 if necessary. If av.Err is not nil, the function returns the error immediately. It uses a type switch to differentiate between uint64 and string types. If the type is string, it tries to parse the string to a uint64. If both assertions fail, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - uint64: The uint64 value after conversion. - error: An optional error if something went wrong during type assertion or parsing, or if av.Err is not nil.
func (AnyValue) AsUint8 ¶ added in v0.1.10
AsUint8 tries to interpret the stored value as a uint8, handling string conversion to uint8 if necessary. If av.Err is not nil, the function returns the error immediately. It uses a type switch to differentiate between uint8 and string types. If the type is string, it tries to parse the string to a uint8. If both assertions fail, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - uint8: The uint8 value after conversion. - error: An optional error if something went wrong during type assertion or parsing, or if av.Err is not nil.
func (AnyValue) Bool ¶ added in v0.1.10
Bool attempts to convert the stored value to a boolean and returns it, along with any error. If av.Err is not nil, the function returns the error immediately. If the type assertion to bool fails, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - bool: The boolean value stored in the struct. - error: An optional error if something went wrong during type assertion or if av.Err is not nil.
func (AnyValue) BoolOrDefault ¶ added in v0.1.10
BoolOrDefault returns the stored value as a boolean, or a default value if there is an error. It reuses the Bool method to get the value and checks for any errors. If an error is encountered, it returns the provided default value.
Parameters: - def bool: The default boolean value to return if there is an error. Returns: - bool: The boolean value stored in the struct or the default value if an error occurs.
func (AnyValue) Bytes ¶ added in v0.1.10
Bytes attempts to convert the stored value to a byte slice ([]byte) and returns it, along with any error. If av.Err is not nil, the function returns the error immediately. If the type assertion to []byte fails, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - []byte: The byte slice value stored in the struct. - error: An optional error if something went wrong during type assertion or if av.Err is not nil.
func (AnyValue) BytesOrDefault ¶ added in v0.1.10
BytesOrDefault returns the stored value as a byte slice ([]byte), or a default value if there is an error. It reuses the Bytes method to get the value and checks for any errors. If an error is encountered, it returns the provided default value.
Parameters: - def []byte: The default byte slice to return if there is an error. Returns: - []byte: The byte slice value stored in the struct or the default value if an error occurs.
func (AnyValue) Float32 ¶ added in v0.1.10
Float32 attempts to convert the stored value to a float32 and returns it, along with any error. If av.Err is not nil, the function returns the error immediately. If the type assertion to float32 fails, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - float32: The float32 value stored in the struct. - error: An optional error if something went wrong during type assertion or if av.Err is not nil.
func (AnyValue) Float32OrDefault ¶ added in v0.1.10
Float32OrDefault returns the stored value as a float32, or a default value if there is an error. It reuses the Float32 method to get the value and checks for any errors. If an error is encountered, it returns the provided default value.
Parameters: - def float32: The default float32 value to return if there is an error. Returns: - float32: The float32 value stored in the struct or the default value if an error occurs.
func (AnyValue) Float64 ¶ added in v0.1.10
Float64 attempts to convert the stored value to a float64 and returns it, along with any error. If av.Err is not nil, the function returns the error immediately. If the type assertion to float64 fails, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - float64: The float64 value stored in the struct. - error: An optional error if something went wrong during type assertion or if av.Err is not nil.
func (AnyValue) Float64OrDefault ¶ added in v0.1.10
Float64OrDefault returns the stored value as a float64, or a default value if there is an error. It reuses the Float64 method to get the value and checks for any errors. If an error is encountered, it returns the provided default value.
Parameters: - def float64: The default float64 value to return if there is an error. Returns: - float64: The float64 value stored in the struct or the default value if an error occurs.
func (AnyValue) Int ¶ added in v0.1.10
Int attempts to convert the stored value to an int and returns it, along with any error. If av.Err is not nil, the function returns the error immediately. If the type assertion to int fails, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - int: The integer value stored in the struct - error: An optional error if something went wrong during type assertion or if av.Err is not nil
func (AnyValue) Int16 ¶ added in v0.1.10
Int16 attempts to convert the stored value to an int16 and returns it, along with any error. If av.Err is not nil, the function returns the error immediately. If the type assertion to int16 fails, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - int16: The int16 value stored in the struct. - error: An optional error if something went wrong during type assertion or if av.Err is not nil.
func (AnyValue) Int16OrDefault ¶ added in v0.1.10
Int16OrDefault returns the stored value as an int16, or a default value if there is an error. It reuses the Int16 method to get the value and checks for any errors. If an error is encountered, it returns the provided default value.
Parameters: - def int16: The default int16 value to return if there is an error. Returns: - int16: The int16 value stored in the struct or the default value if an error occurs.
func (AnyValue) Int32 ¶ added in v0.1.10
Int32 attempts to convert the stored value to an int32 and returns it, along with any error. If av.Err is not nil, the function returns the error immediately. If the type assertion to int32 fails, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - int32: The int32 value stored in the struct. - error: An optional error if something went wrong during type assertion or if av.Err is not nil.
func (AnyValue) Int32OrDefault ¶ added in v0.1.10
Int32OrDefault returns the stored value as an int32, or a default value if there is an error. It reuses the Int32 method to get the value and checks for any errors. If an error is encountered, it returns the provided default value.
Parameters: - def int32: The default int32 value to return if there is an error. Returns: - int32: The int32 value stored in the struct or the default value if an error occurs.
func (AnyValue) Int64 ¶ added in v0.1.10
Int64 attempts to convert the stored value to an int64 and returns it, along with any error. If av.Err is not nil, the function returns the error immediately. If the type assertion to int64 fails, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - int64: The int64 value stored in the struct. - error: An optional error if something went wrong during type assertion or if av.Err is not nil.
func (AnyValue) Int64OrDefault ¶ added in v0.1.10
Int64OrDefault returns the stored value as an int64, or a default value if there is an error. It reuses the Int64 method to get the value and checks for any errors. If an error is encountered, it returns the provided default value.
Parameters: - def int64: The default int64 value to return if there is an error. Returns: - int64: The int64 value stored in the struct or the default value if an error occurs.
func (AnyValue) Int8 ¶ added in v0.1.10
Int8 attempts to convert the stored value to an int8 and returns it, along with any error. If av.Err is not nil, the function returns the error immediately. If the type assertion to int8 fails, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - int8: The int8 value stored in the struct - error: An optional error if something went wrong during type assertion or if av.Err is not nil
func (AnyValue) Int8OrDefault ¶ added in v0.1.10
Int8OrDefault returns the stored value as an int8, or a default value if there is an error. It reuses the Int8 method to get the value and checks for any errors. If an error is encountered, it returns the provided default value.
Parameters: - def int8: The default int8 value to return if there is an error Returns: - int8: The int8 value stored in the struct or the default value if an error occurs
func (AnyValue) IntOrDefault ¶ added in v0.1.10
IntOrDefault returns the stored value as an int, or a default value if there is an error. It reuses the Int method to get the value and checks for any errors. If an error is encountered, it returns the provided default value.
Parameters: - def int: The default integer value to return if there is an error Returns: - int: The integer value stored in the struct or the default value if an error occurs
func (AnyValue) JSONScan ¶ added in v0.1.10
JSONScan converts the stored byte slice (or string) to a JSON object and unmarshals it into the provided value. It first uses the AsBytes method to get the byte slice from the stored value. If successful, it unmarshals the byte slice into the provided value using json.Unmarshal.
Parameters: - val any: The value to which the JSON data should be unmarshalled. Returns: - error: An optional error if something went wrong during conversion or unmarshalling.
func (AnyValue) String ¶ added in v0.1.10
String attempts to convert the stored value to a string and returns it, along with any error. If av.Err is not nil, the function returns the error immediately. If the type assertion to string fails, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - string: The string value stored in the struct. - error: An optional error if something went wrong during type assertion or if av.Err is not nil.
func (AnyValue) StringOrDefault ¶ added in v0.1.10
StringOrDefault returns the stored value as a string, or a default value if there is an error. It reuses the String method to get the value and checks for any errors. If an error is encountered, it returns the provided default value.
Parameters: - def string: The default string value to return if there is an error. Returns: - string: The string value stored in the struct or the default value if an error occurs.
func (AnyValue) Uint ¶ added in v0.1.10
Uint attempts to convert the stored value to a uint and returns it, along with any error. If av.Err is not nil, the function returns the error immediately. If the type assertion to uint fails, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - uint: The unsigned integer value stored in the struct - error: An optional error if something went wrong during type assertion or if av.Err is not nil
func (AnyValue) Uint16 ¶ added in v0.1.10
Uint16 attempts to convert the stored value to a uint16 and returns it, along with any error. If av.Err is not nil, the function returns the error immediately. If the type assertion to uint16 fails, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - uint16: The uint16 value stored in the struct. - error: An optional error if something went wrong during type assertion or if av.Err is not nil.
func (AnyValue) Uint16OrDefault ¶ added in v0.1.10
Uint16OrDefault returns the stored value as a uint16, or a default value if there is an error. It reuses the Uint16 method to get the value and checks for any errors. If an error is encountered, it returns the provided default value.
Parameters: - def uint16: The default uint16 value to return if there is an error. Returns: - uint16: The uint16 value stored in the struct or the default value if an error occurs.
func (AnyValue) Uint32 ¶ added in v0.1.10
Uint32 attempts to convert the stored value to a uint32 and returns it, along with any error. If av.Err is not nil, the function returns the error immediately. If the type assertion to uint32 fails, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - uint32: The uint32 value stored in the struct. - error: An optional error if something went wrong during type assertion or if av.Err is not nil.
func (AnyValue) Uint32OrDefault ¶ added in v0.1.10
Uint32OrDefault returns the stored value as a uint32, or a default value if there is an error. It reuses the Uint32 method to get the value and checks for any errors. If an error is encountered, it returns the provided default value.
Parameters: - def uint32: The default uint32 value to return if there is an error. Returns: - uint32: The uint32 value stored in the struct or the default value if an error occurs.
func (AnyValue) Uint64 ¶ added in v0.1.10
Uint64 attempts to convert the stored value to a uint64 and returns it, along with any error. If av.Err is not nil, the function returns the error immediately. If the type assertion to uint64 fails, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - uint64: The uint64 value stored in the struct. - error: An optional error if something went wrong during type assertion or if av.Err is not nil.
func (AnyValue) Uint64OrDefault ¶ added in v0.1.10
Uint64OrDefault returns the stored value as a uint64, or a default value if there is an error. It reuses the Uint64 method to get the value and checks for any errors. If an error is encountered, it returns the provided default value.
Parameters: - def uint64: The default uint64 value to return if there is an error. Returns: - uint64: The uint64 value stored in the struct or the default value if an error occurs.
func (AnyValue) Uint8 ¶ added in v0.1.10
Uint8 attempts to convert the stored value to a uint8 and returns it, along with any error. If av.Err is not nil, the function returns the error immediately. If the type assertion to uint8 fails, it returns a custom error indicating the value type mismatch.
Parameters: None Returns: - uint8: The uint8 value stored in the struct. - error: An optional error if something went wrong during type assertion or if av.Err is not nil.
func (AnyValue) Uint8OrDefault ¶ added in v0.1.10
Uint8OrDefault returns the stored value as a uint8, or a default value if there is an error. It reuses the Uint8 method to get the value and checks for any errors. If an error is encountered, it returns the provided default value.
Parameters: - def uint8: The default uint8 value to return if there is an error. Returns: - uint8: The uint8 value stored in the struct or the default value if an error occurs.
func (AnyValue) UintOrDefault ¶ added in v0.1.10
UintOrDefault returns the stored value as a uint, or a default value if there is an error. It reuses the Uint method to get the value and checks for any errors. If an error is encountered, it returns the provided default value.
Parameters: - def uint: The default unsigned integer value to return if there is an error Returns: - uint: The unsigned integer value stored in the struct or the default value if an error occurs
type Context ¶
type Context struct {
// Request is the original http.Request object. It represents the HTTP request
// received by the server and contains properties such as the URL, headers,
// query parameters, etc. Handlers can access this to read request data.
Request *http.Request
// ResponseWriter is an interface used to respond to an HTTP request.
// It is the writer that sends the HTTP response back to the client. Handlers use
// this to write the response headers and response body.
ResponseWriter http.ResponseWriter
// PathParams contains any URL path parameters matched by the routing mechanism.
// For example, in a route defined as "/users/:id", the "id" would be available
// in this map for the path "/users/123".
PathParams map[string]string
// Keys is a map for storing arbitrary data that can be shared across different
// parts of the application during the request lifecycle. It is useful for setting
// and getting values that are pertinent to the current HTTP request.
Keys map[string]any
// MatchedRoute is the pattern of the route that matched the current request.
// For example, if the request is to "/users/view" and a "/users/:action" route
// matches it, this field will hold that pattern "/users/:action".
MatchedRoute string
// RespData is a buffer to hold the data that will be written to the HTTP response.
// This is used to accumulate the response body prior to writing to the
// ResponseWriter.
RespData []byte
// RespStatusCode is the HTTP status code that should be sent with the response.
// This is used to store the intended status code which will be written to the
// response during the final handling of the request.
RespStatusCode int
// UserValues is a flexible storage area provided for the developer to store
// any additional values that might be needed throughout the life of the request.
// It is essentially a map that can hold values of any type, indexed by string keys.
UserValues map[string]any
// Aborted is a flag indicating whether the request handling should be stopped.
// If true, handlers should terminate further processing immediately.
Aborted bool
// contains filtered or unexported fields
}
Context is a custom type designed to carry the state and data needed to process an HTTP request within the application. It provides context around the HTTP request, including both the request and response information, as well as additional data needed by handlers to fulfill the request.
func GetContext ¶ added in v0.1.21
GetContext 从对象池获取一个Context 注意:使用后必须调用ReleaseContext归还
func InitContext ¶ added in v0.1.21
InitContext初始化一个新的Context实例
func (*Context) AbortWithStatus ¶ added in v0.0.22
func (*Context) BindJSON ¶
BindJSON deserializes the JSON-encoded request body into the provided value. It is often used in the context of HTTP handlers to parse incoming JSON data into a Go data structure.
Parameters:
- 'val' is a pointer to any Go data structure into which the JSON body of the request will be decoded. This argument must be a non-nil pointer that points to an allocatable or allocated value so that the JSON package can populate the fields of the structure. It must not be nil, as passing nil does not provide a storage location for the decoded data.
The function execution involves the following steps:
- It checks if 'val' is nil. If it is, no storage is allocated for the JSON data to be decoded into, so it returns an error using 'errs.ErrInputNil()', indicating that the input value cannot be nil.
- It checks if 'c.Request.Body' is nil. If the body is nil, there is no data to decode, and it returns an error using 'errs.ErrBodyNil()', signaling that there is no request body to parse.
- It creates a new JSON decoder for the request body and performs the decoding operation using 'decoder.Decode(val)'. If the JSON data in the request body is not well-formed or does not match the expected structure of 'val', json.Decoder will return a relevant error to inform the call site about the issue.
Return Value: - If the decoding is successful, it returns 'nil', indicating that the JSON data has been successfully bound to 'val'. - If an error occurs during decoding, it returns the error, indicating an issue with input validation or the decoding process.
Usage:
- This method is useful when you want to automatically handle the parsing of JSON data into a Go data structure from an HTTP request. It abstracts away the low-level streaming and decoding of JSON.
Example: - To bind the JSON body of an HTTP request to a struct:
type UserInput struct {
Name string `json:"name"`
Email string `json:"email"`
}
var userInput
if err := c.BindJSON(&userInput); err != nil {
// handle the error (e.g., send an HTTP 400 Bad Request response)
}
Note:
- The 'BindJSON' method should be called before accessing the request body by any other means, as the body is an io.ReadCloser and can generally only be read once. Reading the body elsewhere before calling 'BindJSON' will likely result in an EOF error.
func (*Context) BindJSONOpt ¶
BindJSONOpt deserializes the JSON-encoded request body into the provided value with options to use JSON numbers and disallow unknown fields. This function extends the BindJSON method by providing additional decoding options that can be enabled as needed.
Parameters:
- 'val' is a pointer to any Go data structure into which the JSON body of the request will be decoded. It must be a non-nil pointer, so it can be populated with decoded data. Passing a nil pointer will result in an error since there would be no allocated structure to decode the data into.
- 'useNumber' is a boolean option that, when set to true, tells the decoder to decode numbers into an interface{} as a json.Number instead of as a float64. This is useful when precision for large integers is necessary or when the numeric values need to be unmarshalled into a specific typed variable later.
- 'disableUnknown' is a boolean option that, when set to true, causes the decoder to return an error if it encounters any unknown fields in the JSON data that do not match any fields in the target Go data structure. This can be useful for strict input validation.
The function performs the following steps:
- It verifies that 'val' is not nil. If it is nil, it returns an error signaling that a valid pointer is required.
- It checks if 'c.Request.Body' is nil, which would indicate that there is no data to decode, and returns an error if this is the case.
- It initializes a JSON decoder for the request body. The decoder then checks the 'useNumber' and 'disableUnknown' options to configure its behavior accordingly: a. If 'useNumber' is true, it configures the decoder to treat numbers as json.Number types instead of defaulting them to float64. b. If 'disableUnknown' is true, it configures the decoder to reject unknown fields.
- It attempts to decode the JSON request body into 'val'. If the decoding is unsuccessful (for example, due to JSON syntax errors, mismatch between the JSON data and 'val' structure, etc.), it returns the error resulting from the decoder.
Return Value: - Returns 'nil' if the JSON request body has been successfully decoded into 'val'. - Returns an error if 'val' is nil, if there is no request body, or if the JSON decoding process encounters an error.
Usage: - This method is useful for controlling the JSON decoding process in HTTP handlers where there may be a need for more strict or lenient JSON parsing.
Example: - To bind a JSON body to a struct with strict type preservation and unknown field rejection:
type UserInput struct {
Name string `json:"name"`
Age json.Number `json:"age"`
}
var userInput
err := c.BindJSONOpt(&userInput, true, true)
if err != nil {
// handle the error (e.g., send an HTTP 400 Bad Request response)
}
Note:
- Similar to BindJSON, BindJSONOpt should be called before any other form of accessing the request body is performed, as it is an io.ReadCloser that allows for a single read operation. This means that calling BindJSONOpt after the body has been read will likely result in an EOF error.
func (*Context) ClientIP ¶ added in v0.0.21
ClientIP attempts to determine the client's IP address from the request headers in the following order: 1. X-Forwarded-For header (a common header used in proxy setups). 2. X-Real-IP header (another header used in some proxy setups). 3. If neither of the above headers are present, it falls back to the remote IP address derived from the RemoteAddr field. Returns: - string: The determined client IP address.
func (*Context) Done ¶ added in v0.1.9
func (c *Context) Done() <-chan struct{}
Done 返回一个通道,当上下文取消或超时时关闭
func (*Context) FormValue ¶
FormValue extracts a value from the form data in an HTTP request based on the given key. It parses the URL-encoded form data (both in the URL query string and the request body) and retrieves the value associated with the provided key.
Parameters: - 'key' is a string representing the name of the form value to be retrieved from the HTTP request.
The function performs the following actions:
- It calls 'c.Request.ParseForm()' to parse the request body as a URL-encoded form. This is necessary to populate 'c.Request.Form' with the form data. This method also parses the query parameters from the URL, merging them into the form values. If parsing fails (for example, if the body can't be read, is too large, or if the content type is not application/x-www-form-urlencoded), an error is returned.
- If 'ParseForm()' returns an error, the function creates a 'AnyValue' instance with an empty string for 'val' and the parsing error for 'err'. It then returns this 'AnyValue' containing the error information.
- If 'ParseForm()' succeeds, 'c.Request.FormValue(key)' is used to retrieve the first value for the specified key from the merged form data. A 'AnyValue' instance is then returned with the retrieved value and 'nil' for the error.
Return Value:
- A 'AnyValue' instance is always returned. This struct contains two fields: a. 'Val' which is the any value retrieved from the form data. b. 'Err' which captures any error that may have occurred during the parsing of the form data.
Usage: - This method is intended to be used in HTTP handlers when you need to access form values sent in an HTTP request.
Example: - To retrieve a form value named "email" from an HTTP request:
email := c.FormValue("email")
if email.err != nil {
// handle the error (e.g., send an HTTP 400 Bad Request response)
}
// Use email.val as the required string value for "email".
Note:
- The 'FormValue' method does not handle multiple values for the same key. It only retrieves the first such value.
- Calling 'FormValue' multiple times on the same request is safe as it does not reparse the form data. The form data is parsed only once, and subsequent calls will retrieve values from the already parsed form.
- The 'ParseForm' method can only parse the request body if the method is "POST" or "PUT" and the content type is "application/x-www-form-urlencoded". For other HTTP methods or content types, the body will not be parsed, but URL query parameters will still be available.
Considerations: - Ensure that the 'ParseForm' method is not called before any other method that might consume the request body, as the request body is typically read-only once.
func (*Context) Get ¶ added in v0.0.22
Get retrieves a value stored in the context under the specified key. It returns the value and a boolean indicating whether the key exists in the map. This method is safe for concurrent use by multiple goroutines. Parameters: - key: the string key under which the value is stored. Returns: - value: the value stored under the key; nil if the key does not exist. - exists: a boolean indicating whether the key exists in the map.
func (*Context) GetBool ¶ added in v0.0.22
GetBool retrieves a boolean value associated with the given key from the context. Parameters: - key: The key to retrieve the value for (string). Returns: - bool: The boolean value associated with the key, or false if the key does not exist or is not a boolean.
func (*Context) GetDuration ¶ added in v0.0.22
GetDuration retrieves a time.Duration value associated with the given key from the context. Parameters: - key: The key to retrieve the value for (string). Returns: - time.Duration: The time.Duration value associated with the key, or 0 if the key does not exist or is not a time.Duration.
func (*Context) GetFloat64 ¶ added in v0.0.22
GetFloat64 retrieves a float64 value associated with the given key from the context. Parameters: - key: The key to retrieve the value for (string). Returns: - float64: The float64 value associated with the key, or 0 if the key does not exist or is not a float64.
func (*Context) GetInt ¶ added in v0.0.22
GetInt retrieves an integer value associated with the given key from the context. Parameters: - key: The key to retrieve the value for (string). Returns: - int: The integer value associated with the key, or 0 if the key does not exist or is not an integer.
func (*Context) GetInt64 ¶ added in v0.0.22
GetInt64 retrieves an int64 value associated with the given key from the context. Parameters: - key: The key to retrieve the value for (string). Returns: - int64: The int64 value associated with the key, or 0 if the key does not exist or is not an int64.
func (*Context) GetString ¶ added in v0.0.22
GetString retrieves a string value associated with the given key from the context. Parameters: - key: The key to retrieve the value for (string). Returns: - string: The string value associated with the key, or an empty string if the key does not exist or is not a string.
func (*Context) GetStringMap ¶ added in v0.0.22
GetStringMap retrieves a map with string keys and any type values associated with the given key from the context. Parameters: - key: The key to retrieve the value for (string). Returns: - map[string]any: The map associated with the key, or nil if the key does not exist or is not a map.
func (*Context) GetStringMapString ¶ added in v0.0.22
GetStringMapString retrieves a map with string keys and string values associated with the given key from the context. Parameters: - key: The key to retrieve the value for (string). Returns: - map[string]string: The map associated with the key, or nil if the key does not exist or is not a map with string values.
func (*Context) GetStringMapStringSlice ¶ added in v0.0.22
GetStringMapStringSlice retrieves a map with string keys and slice of string values associated with the given key from the context. Parameters: - key: The key to retrieve the value for (string). Returns: - map[string][]string: The map associated with the key, or nil if the key does not exist or is not a map with slice of string values.
func (*Context) GetStringSlice ¶ added in v0.0.22
GetStringSlice retrieves a slice of strings associated with the given key from the context. Parameters: - key: The key to retrieve the value for (string). Returns: - []string: The slice of strings associated with the key, or nil if the key does not exist or is not a slice of strings.
func (*Context) GetTime ¶ added in v0.0.22
GetTime retrieves a time.Time value associated with the given key from the context. Parameters: - key: The key to retrieve the value for (string). Returns: - time.Time: The time.Time value associated with the key, or the zero value of time.Time if the key does not exist or is not a time.Time.
func (*Context) GetUint ¶ added in v0.0.22
GetUint retrieves an unsigned integer value associated with the given key from the context. Parameters: - key: The key to retrieve the value for (string). Returns: - uint: The unsigned integer value associated with the key, or 0 if the key does not exist or is not an unsigned integer.
func (*Context) GetUint64 ¶ added in v0.0.22
GetUint64 retrieves a uint64 value associated with the given key from the context. Parameters: - key: The key to retrieve the value for (string). Returns: - uint64: The uint64 value associated with the key, or 0 if the key does not exist or is not a uint64.
func (*Context) Header ¶ added in v0.0.22
Header sets or deletes a specific header in the HTTP response. If the given value is an empty string, the header is deleted. Otherwise, the value is set for the given key. Parameters: - key: the header name to set or delete. - value: the header value to set; if empty, the header with the given key is deleted.
func (*Context) MustGet ¶ added in v0.0.22
MustGet returns the value for the given key if it exists, otherwise it panics.
func (*Context) PathValue ¶
PathValue retrieves a value from the path parameters of an HTTP request based on the given key. The path parameters are typically extracted from the URL path, where they are defined by the routing patterns used in the application.
Parameters: - 'key': A string representing the name of the path parameter to be retrieved.
The function performs the following actions:
- It checks if the map 'c.PathParams' contains the key provided in the method parameter. 'c.PathParams' is expected to be populated with key-value pairs where keys correspond to path parameter names defined in the URL pattern, and values are the respective parameters extracted from the actual request URL.
- If the key is present in 'c.PathParams', it retrieves the corresponding value, wraps it in a 'AnyValue' struct by setting the 'val' field to the retrieved value and 'err' field to nil, and then returns it.
- If the key is not found, it means the requested path parameter is not present in the request URL. In this case, the method returns a 'AnyValue' struct with 'val' set to an empty string and 'err' set to an error instance that typically indicates the absence of the key.
Return Value:
- A 'AnyValue' struct that contains the value associated with the provided key ('val') and an error field ('err'). If the key is not present, the 'err' field contains an appropriate error while 'val' is an empty string.
Usage: - This method is useful in web server routing where URL paths may contain parameters that need to be extracted and used within the application logic.
Example: - Assuming a URL pattern like "/users/:id" where :id is a path parameter:
userID := c.PathValue("id")
if userID.err != nil {
// handle the error (e.g., send an HTTP 404 Not Found response)
}
// Use userID.val as the required user ID string value.
Note:
- The method assumes that 'c.PathParams' has already been populated with the correct path parameters before calling 'PathValue'. In a typical web server implementation, this population is done during the routing process, before the request handler is invoked.
- The 'PathParams' may hold multiple path parameters depending on the URL pattern; 'PathValue' method is responsible for extracting a single parameter by key.
- If the same key was present multiple times in 'c.PathParams', this method would return the first instance of the value associated with the key.
Considerations:
- When working with frameworks or routers that facilitate path parameter extraction, ensure the router is correctly configured to parse and store the path parameters before calling this method.
func (*Context) QueryValue ¶
QueryValue retrieves the first value associated with the specified key from the URL query parameters of an HTTP request.
Parameters: - 'key' is the string that specifies the key in the query parameter that we want to retrieve the value for.
This function operates as follows:
- Checks if 'c.queryValues' is already populated. If it is not, it initializes it with the parsed query parameters obtained by calling 'c.Request.URL.Query()'. This method parses the raw query from the URL and returns a map of the query parameters.
- It looks for the given 'key' in 'c.queryValues' to see if it exists. The values are stored in a slice of strings because URL query parameters can have multiple values.
- If the key does not exist in the map, it implies that the parameter was not supplied in the query string. In this case, the function returns a 'AnyValue' struct with an empty string for the 'val' field and an 'ErrKeyNil' error for the 'err' field.
- If the key is present, the function returns a 'AnyValue' struct with the first value associated with the key and 'nil' for the 'err' field.
Return Value:
- A 'AnyValue' struct is always returned. It contains: a. 'val', the value associated with the provided key from the query parameters. b. 'err', an error if the key is not found in the query parameters.
Usage: - The method is ideal when you need to obtain individual query parameters from an HTTP request without parsing the entire URL query string manually.
Example: - To retrieve a query parameter named "page" from an HTTP request:
page := c.QueryValue("page")
if page.err != nil {
// handle the error (e.g., the "page" query parameter was not provided)
}
// Use page.val to work with the value of "page".
Note:
- This function only retrieves the first value for the specified key even if there are multiple values for that key.
- 'c.queryValues' is cached after its first use, which improves performance when accessing multiple query parameters since it avoids reparsing the query string of the URL.
- It is important to correctly handle the error scenario since a missing key in the query parameters can affect application logic.
Considerations: - While handling query data, consider the URL's sensitivity and the possibility of multiple values. Always validate and clean data from URL queries to ensure security.
func (*Context) RemoteIP ¶ added in v0.0.21
RemoteIP extracts the remote IP address from the context's request. It uses the RemoteAddr field from the request, which typically contains both the IP address and port. This method extracts and returns just the IP address part. Returns: - string: The remote IP address, or an empty string if extraction fails.
func (*Context) Render ¶
Render processes a template and populates it with dynamic data provided by the 'data' parameter. The method first attempts to render the specified template by calling the rendering engine bound to the context.
Parameters:
- 'templateName' is the name of the template that should be rendered. It is expected that this template has been defined and is recognizable by the template engine.
- 'data' is an interface{} type, which means it can accept any value that conforms to Go's empty interface. This is the dynamic content that will be injected into the template during rendering.
The rendered template output is captured and assigned to 'c.RespData'. This output will typically be HTML or another text format suitable for the client's response.
If the rendering operation is successful, the response status code is set to HTTP 200 (OK) indicating the request has been successfully processed and the client can expect valid content.
If an error occurs during the rendering operation (such as if the template is not found, or if there is a problem with the template's syntax), the response status code is set to HTTP 500 (Internal Server Error), and the error is returned to the caller. This error should be handled appropriately by the caller, possibly by logging it or presenting a user-friendly error message to the end-user.
Return Value: Returns 'nil' if rendering succeeds without any error, otherwise an error object describing the rendering failure is returned.
func (*Context) RespondSuccess ¶ added in v0.1.15
RespondSuccess sends a JSON response with an HTTP status code 200 (OK) to the client. This is a convenience method that wraps around the more general 'RespJSON' method, abstracting the common case of responding with an OK status.
Parameters:
- 'val' is the data of any type that will be serialized into JSON format. The 'val' can be any Go data structure, including structs, maps, slices, and primitive types. It is important that the 'val' can be marshaled into JSON; otherwise, the serialization will fail.
Internally, 'RespJSONOK' calls the 'RespJSON' method on the same context instance 'c', passing in 'http.StatusOK' as the status code and 'val' as the value to be serialized.
The 'RespJSON' method handles the serialization of 'val' to JSON, sets the "Content-Type" response header to "application/json", and writes the JSON-encoded data to the response along with the provided HTTP status code.
Return Value: - If the serialization into JSON is successful and the response is written to the client, it returns 'nil' indicating no error occurred. - In case of an error during JSON marshaling or writing to the response, it returns an error detailing the issue encountered.
Usage:
- This method is typically used within an HTTP handler function when the server needs to send a JSON response back to the client with a 200 OK status code. This is usually the case when a request has been processed successfully, and server needs to inform the client of the success, often with accompanying data.
Example: - To send a simple success message in JSON format:
type response struct {
Message string `json:"message"`
}
resp := response{Message: "Data processed successfully"}
err := c.RespJSONOK(resp)
if err != nil {
// handle error
}
Note: - This method should be called after all response headers and status codes are set, and before any calls to write body content directly, as it will write data to the body and set headers.
func (*Context) RespondWithJSON ¶ added in v0.1.15
RespondWithJSON sends a JSON-formatted response to the client with a specified HTTP status code. It converts the provided value to JSON, sets the response headers, and writes the JSON data to the response.
Parameters:
- 'status' is an integer that represents the HTTP status code to send with the response. Standard HTTP status codes should be used (e.g., 200 for OK, 400 for Bad Request, 404 for Not Found, etc.).
- 'val' is an interface{} (any type) that holds the data to be serialized into JSON. This can be any Go data structure such as structs, slices, maps, etc. The value provided must be a valid input for the json.Marshal function, which means it should be able to be encoded into JSON. Non-exported struct fields will be omitted by the marshaller.
This function performs several actions:
- It uses the 'json.Marshal' function to serialize the 'val' parameter into a JSON-formatted byte slice 'data'. If marshaling fails, it returns the resultant error without writing anything to the response.
- Assuming marshaling is successful, it sets the "Content-Type" header of the response to "application/json" to inform the client that the server is returning JSON-formatted data.
- It sets the "Content-Length" header to the length of the serialized JSON data, which helps the client understand how much data is being transmitted.
- It writes the HTTP status code to the response using WriteHeader(status). This must be done before writing the response body.
- Lastly, it assigns the JSON data to 'c.RespData' and the status code to 'c.RespStatusCode' for later use or inspection.
Return Value: - If the JSON serialization and writing to the response are successful, it returns 'nil', indicating that the operation completed without error. - If an error occurs during JSON serialization, the error is returned, and no further action is taken.
Usage: - This method is designed to be used in HTTP handler functions where a JSON response is needed. It abstracts away the common tasks of JSON serialization, header setting, and response writing.
Example: - To send an object with an OK (200) status code:
data := map[string]string{"status": "success"}
err := c.RespJSON(http.StatusOK, data)
if err != nil {
log.Printf("Error sending JSON response: %v", err)
// handle the error, like sending a 500 Internal Server Error status code
}
Note:
- It is important to note that once the 'WriteHeader' method is called, it's not possible to change the response status code or write any new headers. Also, care must be taken to ensure that 'RespJSON' is not called after the response body has started to be written by other means, as this would result in an HTTP protocol error.
func (*Context) RespondWithJSONBuffer ¶ added in v0.1.21
RespondWithJSONBuffer 使用缓冲区池来优化JSON响应
func (*Context) Set ¶ added in v0.0.22
Set stores a value in the context under the specified key. This method is safe for concurrent use by multiple goroutines. Parameters: - key: the string key under which to store the value. - value: the value to be stored, which can be of any type.
func (*Context) SetCookie ¶
SetCookie adds a Set-Cookie header to the response of the current HTTP context. This method is used to send cookies from the server to the client's web browser.
Parameters: - 'ck' is a pointer to an 'http.Cookie' object which represents the cookie you want to set. This object includes various fields that define the properties of a cookie, such as Name, Value, Path, Domain, Expires, and so on.
This function does not return any value or error, as it directly manipulates the HTTP headers of the response. It's essential to call SetCookie before writing any response body to the client because HTTP headers cannot be modified after the body starts to be written.
'http.SetCookie' is a standard library function that ensures the correct formatting of the Set-Cookie header. When calling this method, 'c.ResponseWriter' is used to gain access to the response writer associated with the current HTTP request handled by the context 'c'.
Usage:
- This method is typically called within an HTTP handler function where you have an instance of the Context 'c' available. It is part of managing session data, sending tracking cookies, or setting any other kind of cookie data required by the application.
Example: - To set a session cookie with a session identifier:
sessionCookie := &http.Cookie{
Name: "session_id",
Value: "abc123",
Expires: time.Now().Add(24 * time.Hour),
Path: "/",
}
c.SetCookie(sessionCookie)
Note: - If you need to set multiple cookies, you would call this method multiple times, passing in each cookie as a separate 'http.Cookie' object.
func (*Context) WithTimeout ¶ added in v0.1.21
WithTimeout 为当前上下文设置新的超时时间
type FileDownloader ¶
type FileDownloader struct {
Dir string
}
FileDownloader is a structure that encapsulates the necessary information for handling file download operations in a web application setting. The struct is designed to provide a foundation for methods that allow users to download files from a specified directory on the server. It acts primarily as a configuration container for the download directory, with the potential to extend functionality for more advanced features like path resolution, access control, and download logging.
Fields:
- Dir string: Specifies the root directory from which files will be served. This path should be an absolute path or a relative path to the directory that the server process has access to. All file download requests will be resolved relative to this directory, meaning that file paths provided in download requests should be relative to this 'Dir' directory. It is important to consider security implications when defining this directory, to prevent unauthorized access to sensitive files. File access should be properly managed to avoid directory traversal attacks or the exposure of restricted files.
Usage Notes: An instance of FileDownloader should be initialized with the 'Dir' field set to the directory containing the files to be downloaded. This instance can then be integrated into the web application's server side, where a corresponding handler function will use the information contained within FileDownloader to resolve and serve file download requests. The handler will typically interpret the file path from the incoming HTTP request, ensure that it points to a valid file within the 'Dir', and then stream that file back to the client with the appropriate Content-Disposition header to prompt a file download in the client's browser.
Example Implementation:
downloader := &FileDownloader{
Dir: "/var/www/downloads",
}
This downloader instance could then be referenced in a dedicated route's handler function to process file download requests, ensuring all downloads are served from the "/var/www/downloads" directory.
func (*FileDownloader) Handle ¶
func (f *FileDownloader) Handle() HandleFunc
Handle creates and returns a HandleFunc designed for serving files for download. This HTTP handler ensures that the files served for download are securely retrieved from a specified server directory and delivered to the client correctly. The handler takes care to resolve the file path, validate the request, and to set proper HTTP headers to facilitate the file download on the client side.
The HandleFunc performs the following steps:
- Extracts the 'file' query parameter from the request's URL. This parameter contains the relative path to the file that the client wants to download.
- If the 'file' query parameter is missing or another error occurs while retrieving it, the handler responds with an HTTP 400 Bad Request status and a message indicating that the destination file could not be found.
- Cleans up the requested file path using filepath.Clean to prevent any directory traversal attempts and ensure the path is in its simplest form.
- Joins the cleaned file path with the FileDownloader's Dir to form an absolute path to the file within the server's file system.
- Converts the resulting path to an absolute path and checks if the resolved file path actually exists within the designated download directory. This acts as a security measure to prevent clients from accessing files outside the allowed directory.
- If the resolved file path is outside the designated download directory, the handler responds with an HTTP 400 Bad Request status and a message indicating an access path error.
- The file name is extracted from the resolved path to be used in the Content-Disposition header, which advises the client's browser that a file is expected to be downloaded and saved locally.
- Various HTTP response headers are set to inform the client about the file transfer details: - Content-Disposition: Advises the client on how to handle the file data. - Content-Description: Description of the content. - Content-Type: Specifies that the content is a stream of binary data (i.e., a file). - Content-Transfer-Encoding: Notates that the content transfer will be in binary mode. - Expires: Indicates that the content should not be cached for later use. - Cache-Control and Pragma: Directives to control browser caching.
- The http.ServeFile function is called to serve the file contained in the resolved path to the client. This function takes care of streaming the file data to the client. The function also automatically determines the Content-Type header, although it is overridden here to "application/octet-stream" to trigger the browser's download dialog.
The handler secured by the FileDownloader ensures that only files from a specified directory can be accessed and downloaded by the client. Proper error handling is implemented to return meaningful HTTP status codes and messages to the client in case of an error, such as path resolution issues or illegal file access attempts.
type FileUploader ¶
type FileUploader struct {
FileField string
DstPathFunc func(*multipart.FileHeader) string
}
FileUploader defines a structure used for configuring and handling the upload of files in a web application. It provides a customized way of determining where files should be stored upon upload based on the properties provided. It is particularly useful in scenarios where uploaded files need to be saved to different locations depending on file metadata or other contextual information available at runtime.
Fields:
FileField string: The name of the form field used for the file upload. This corresponds to the 'name' attribute in the HTML form input element for file uploads (e.g., <input type="file" name="myfile">). The FileUploader will look for this specific field in the multipart form data to process the file uploads.
DstPathFunc func(*multipart.FileHeader) string: A functional field used to generate the destination path for an uploaded file. This function takes a pointer to a multipart.FileHeader struct, which contains metadata about an uploaded file (such as filename, size, and content type), and returns a string that represents the destination path where the file should be saved. By allowing the path to be dynamically determined through this function, the FileUploader can achieve more flexible and context-sensitive file storage behavior. This is advantageous when the storage location depends on specific file characteristics or other request-specific data.
Example usage of FileUploader:
uploader := &FileUploader{
FileField: "avatar", // This should match the file input field's name in your form
DstPathFunc: func(fh *multipart.FileHeader) string {
// Generate a unique file name, for instance, by using a UUID generator, and sanitize the original filename
// Colons could be replaced with a timestamp or another identifier as needed for the application.
return filepath.Join("/uploads/avatars", uuid.New().String() + filepath.Ext(fh.Filename))
},
}
The FileUploader struct is typically used in conjunction with HTTP server handlers or middlewares in Go that are responsible for handling file uploads. During the request processing, the FileUploader can be utilized to retrieve the file data associated with its FileField and to invoke DstPathFunc to calculate where the file should be stored. Subsequent steps would typically involve actually storing the file data in the specified location and handling any errors or post-processing tasks as necessary.
func (*FileUploader) Handle ¶
func (f *FileUploader) Handle() HandleFunc
Handle returns a HandleFunc specifically prepared to process file upload requests based on the configuration of the FileUploader struct. This HandleFunc can be used as an HTTP handler that intercepts file upload HTTP requests, processes them, and provides an appropriate response to the client based on the outcome of the operation.
The returned HandleFunc performs the following steps:
- It attempts to retrieve the file data from the request's form field as specified by the FileUploader's FileField.
- If it encounters an error during file retrieval, it sets the HTTP response status code to Internal Server Error (500), and it sends back an error message to the client, indicating that the upload failed, along with the error details.
- Upon successful retrieval of the file, the function then calls the FileUploader's DstPathFunc with the metadata of the uploaded file (fileHeader) to determine the destination path where the file should be saved.
- The function checks for errors from the DstPathFunc call; if there's an error, it responds with an Internal Server Error status and an error message as in step 2.
- Next, it attempts to open (or create if not existing) the destination file for writing. It ensures that the permissions for the new file allow read and write operations for the user, group, and others (permission mode 0666).
- If it cannot open the destination file, it responds with an Internal Server Error status and an error message.
- If the destination file is opened successfully, it then copies the content of the uploaded file to the destination file using an io.CopyBuffer operation. This function performs the copy operation and allows the reuse of an existing slice (buffer) to reduce memory allocation, which is set to nil to use a pre-allocated buffer of a default size.
- Any error encountered during the copy process results in an Internal Server Error status and an error message.
- If the file is uploaded and saved successfully, the function sets the HTTP response status to OK (200) and sends a success message to the client.
It's important that the file handles for both the uploaded file and the destination file are closed properly to release the resources. The defer keyword is used right after each file is opened to ensure that the file handles are closed when the function returns.
Usage of the Handle method would typically involve adding the returned HandleFunc as an HTTP handler in a web server's routing configuration. This would route certain POST requests expected to contain file uploads through this handler to process the file saving task accordingly.
type GoTemplateEngine ¶
type GoTemplateEngine struct {
// T is a pointer to a compiled template object from the Go standard library's template package.
// It stores all the parsed template files that can be executed to generate output based on dynamic data.
T *template.Template
}
GoTemplateEngine is a struct that adheres to the TemplateEngine interface. It represents a concrete implementation using Go's standard library "text/template" or "html/template" for rendering templates. This structure enables the application to perform template rendering operations using Go's built-in template parsing and execution capabilities.
The GoTemplateEngine struct contains a single field:
- T: This field holds a pointer to a template.Template object from Go's template package. The template.Template type is a thread-safe, compiled representation of a set of templates that can be executed with particular data inputs to produce rendered content. This field should be pre-populated with parsed templates upon the creation of a GoTemplateEngine instance.
When initializing a new GoTemplateEngine, the typical process includes parsing the template files or strings using the Parse, ParseFiles, or ParseGlob functions provided by Go's template package. These functions compile the templates and return a *template.Template object, which is then assigned to the T field.
Using the T field, the GoTemplateEngine can execute the named templates with given data using the ExecuteTemplate method, which satisfies the Render method of the TemplateEngine interface. The execution process replaces template tags with corresponding data and generates the final rendered output.
Example of initializing a GoTemplateEngine with parsed templates could look like this:
func NewEngine() (*GoTemplateEngine, error) {
tmpl, err := template.ParseFiles("templates/base.html", "templates/index.html")
if err != nil {
return nil, err
}
return &GoTemplateEngine{T: tmpl}, nil
}
func (*GoTemplateEngine) LoadFromFS ¶
func (g *GoTemplateEngine) LoadFromFS(fs fs.FS, patterns ...string) error
LoadFromFS is a method on the GoTemplateEngine struct that loads and parses templates from a file system abstraction (fs.FS) using specified glob patterns. It updates the GoTemplateEngine's T field with the resulting template set. This allows the loading of templates from various sources that implement the fs.FS interface, such as in-memory file systems, making the method flexible and adaptable to different run-time environments.
Parameters:
- fs.FS: The fs.FS interface instance represents an abstract file system to load templates from. It provides a way to abstract the file system operations through methods like Open, making it possible to work with different file systems (e.g., an actual OS file system, in-memory file systems, embedded file systems).
- patterns ...string: This variadic parameter takes multiple string arguments, each representing a glob pattern used to match files within the provided file system (fs). These patterns tell the method which files to consider when loading and parsing the templates.
Returns:
- error: If there is an issue parsing the templates using the provided file system and patterns, the method will return an error. This error could be a result of file I/O operations issues, files not matching any patterns, permission issues, or problems within the template files such as syntax errors. In the case of an error, the GoTemplateEngine's T field will not be updated with any new templates.
Internally, the method uses the template.ParseFS function from Go's template package. This function is designed to work with the fs.FS interface to read and parse templates. The method parses all the files that match the provided patterns into a template set, which is then stored in the T field of the current GoTemplateEngine instance.
As with other template loading methods, proper error handling is crucial to ensure the application can handle cases where templates could not be loaded. If no errors are returned, the engine can proceed to render these templates through its Render method, as they are immediately available for use.
func (*GoTemplateEngine) LoadFromFiles ¶
func (g *GoTemplateEngine) LoadFromFiles(filenames ...string) error
LoadFromFiles is a method on the GoTemplateEngine struct that parses template files specified by the filenames and updates the GoTemplateEngine's T field with the parsed template set. This method allows for explicit control over which template files are loaded and is commonly used for initializing the engine with a known set of templates or updating the templates at runtime.
Parameters:
- filenames ...string: A variadic parameter that accepts an arbitrary number of strings, each representing the path to a template file that should be included in the parsing process. This allows for a flexible number of files to be loaded at once without needing to specify them in a slice.
Returns:
- error: If the method encounters any issues while trying to read or parse the provided template files, it will return an error. Potential issues include file I/O errors, file not found errors, permission denials, or problems within the template files themselves, such as syntax errors. If an error is returned, the T field remains unchanged, and the new templates are not loaded.
The method makes use of the template.ParseFiles function provided by Go's template package. The ParseFiles function takes the provided file paths, reads the contents, and attempts to parse them into templates within a template set. These templates are then stored in the T field of the GoTemplateEngine.
Error handling after calling this method is essential to ensure the application's stability, as templates are fundamental for generating output based on them. On successful execution, the templates become immediately available for rendering through the engine's Render method.
func (*GoTemplateEngine) LoadFromGlob ¶
func (g *GoTemplateEngine) LoadFromGlob(pattern string) error
LoadFromGlob is a method of GoTemplateEngine that loads and parses template files based on a specified pattern (glob). After execution, the GoTemplateEngine's T field is updated to contain the new parsed templates. This method is typically used during initialization or when the templates need to be refreshed.
Parameter:
- pattern string: The pattern parameter is a string that specifies the glob pattern used to identify the template files that should be parsed and added to the template set. A glob pattern may include wildcards (e.g., "*.tmpl" for all files with the .tmpl extension in the current directory, or "templates/*.html" for all .html files within a 'templates' directory).
Returns:
- error: This function will return an error if the parsing operation fails. The error might be caused by an inability to read files due to incorrect permissions, non-existent files, or syntax errors within the template files themselves. If an error is returned, the T field of the GoTemplateEngine struct is not updated with any new templates.
The method works by invoking template.ParseGlob from Go's template package with the provided pattern string. This function reads and parses all the template files that match the pattern into a new template set. The parsed templates are then assigned to the T field of the GoTemplateEngine instance.
When calling this method, it's important to handle any errors returned to ensure the application is aware if the templates failed to load. A successful execution means that the T field is now ready to execute the loaded templates with the Render method.
func (*GoTemplateEngine) Render ¶
func (g *GoTemplateEngine) Render(ctx context.Context, templateName string, data any) ([]byte, error)
Render is the method that implements the rendering functionality for the GoTemplateEngine. It satisfies the TemplateEngine interface's Render method, allowing the GoTemplateEngine to be used wherever a TemplateEngine is required. This method executes the named template using the provided data and generates a rendered output as a slice of bytes.
Parameters:
- ctx context.Context: This parameter provides context for the render operation. It can carry deadlines, cancellations signals, and other request-scoped values across API boundaries and between processes. In this method, ctx is not directly used but could be utilized by extending the method further to support context-aware operations in the render process, such as logging, tracing, timeout, or cancellation.
- templateName string: The name of the template to be executed. This must correspond to the name given to one of the parsed templates contained within the *template.Template associated with the GoTemplateEngine.
- data any: The data to be applied to the template during rendering. This could be any type of value that the underlying templates are expected to work with, typically a struct, map, or a primitive type that the template fields can reference.
Returns:
- []byte: A byte slice containing the rendered output from the executed template. If rendering is successful without any errors, the content of the slice represents the completed output, ready to be used as needed (e.g., sent as an HTTP response).
- error: An error that may have been encountered during the template execution. If such an error occurs, it's usually related to issues like an undefined template name, missing data for placeholders in the template, or execution errors within the template. If the error is non-nil, the byte slice returned will be nil, and the error should be handled appropriately.
The Render method works by creating a new bytes.Buffer to act as an in-memory writer where the rendered output is temporarily stored. The ExecuteTemplate method of the *template.Template is then called with this buffer, the name of the template, and the data to be used for rendering. If the template execution is successful, the content of the buffer is returned as a byte slice. In case of an error, the error returned from ExecuteTemplate is passed through to the caller.
type HTTP3Config ¶ added in v0.1.27
type HTTP3Config struct {
// QUIC配置
MaxIdleTimeout time.Duration
MaxIncomingStreams int64
MaxIncomingUniStreams int64
// TLS配置
TLSConfig *tls.Config
// 连接配置
EnableDatagrams bool
HandshakeIdleTimeout time.Duration
// Alt-Svc配置
AltSvcHeader string
EnableAltSvcHeader bool
}
HTTP3Config 定义HTTP/3服务器的配置选项
func DefaultHTTP3Config ¶ added in v0.1.27
func DefaultHTTP3Config() *HTTP3Config
DefaultHTTP3Config 返回默认的HTTP/3配置
type HTTP3Server ¶ added in v0.1.27
type HTTP3Server struct {
// contains filtered or unexported fields
}
HTTP3Server 提供HTTP/3服务器功能
func NewHTTP3Server ¶ added in v0.1.27
func NewHTTP3Server(httpServer *http.Server, config *HTTP3Config, logger Logger) *HTTP3Server
NewHTTP3Server 创建新的HTTP/3服务器
func (*HTTP3Server) ListenAndServe ¶ added in v0.1.27
func (s *HTTP3Server) ListenAndServe(addr string) error
ListenAndServe 在指定地址启动HTTP/3服务器
func (*HTTP3Server) ListenAndServeTLS ¶ added in v0.1.27
func (s *HTTP3Server) ListenAndServeTLS(addr, certFile, keyFile string) error
ListenAndServeTLS 使用TLS证书启动HTTP/3服务器
type HTTPServer ¶
type HTTPServer struct {
// contains filtered or unexported fields
}
HTTPServer是一个结构体,定义了Web应用程序中HTTP服务器的基本结构。 它封装了处理HTTP请求所需的组件,如路由、中间件处理、日志记录和模板渲染。 通过将这些功能组织到单个结构体中,它为开发者提供了一个内聚的框架,以高效地管理 服务器的行为并配置其各种组件。 嵌入字段和属性:
router: router是一个嵌入字段,代表服务器的路由机制。作为嵌入字段,
它为HTTPServer提供了直接访问路由方法的能力。router负责
根据URL路径和HTTP方法将传入请求映射到适当的处理函数。
middlewares ([]Middleware): middlewares切片保存服务器将按顺序为每个请求执行的中间件函数。
中间件函数用于拦截和操作请求和响应,允许身份验证、日志记录
和会话管理等任务以模块化方式处理。
log (Logger): log字段是Logger接口的一个实例。这种抽象允许服务器利用各种日志
实现,以标准化的方式灵活记录服务器事件、错误和其他信息。
templateEngine (TemplateEngine): templateEngine字段是一个接口,它抽象了HTML模板
处理和渲染的具体细节。它允许服务器执行模板并提供
动态内容,使得根据应用程序需求轻松集成不同的模板处理
系统成为可能。
用法: 构建HTTPServer时,开发者必须在启动服务器前初始化每个组件:
- router必须设置路由,将URL映射到处理函数。
- 必须按照必要的顺序将中间件函数添加到middlewares切片中,因为它们将按顺序执行。
- 必须为log字段提供Logger实现,以记录服务器操作、错误和其他事件。
- 如果服务器将提供动态HTML内容,必须分配一个符合templateEngine接口的TemplateEngine, 使服务器能够用动态数据渲染HTML模板。
通过确保所有这些组件都被正确初始化,HTTPServer可以高效地管理入站请求, 应用必要的预处理,处理路由,执行业务逻辑,并生成动态响应。
func InitHTTPServer ¶
func InitHTTPServer(opts ...HTTPServerOption) *HTTPServer
InitHTTPServer 初始化并返回一个新的HTTPServer实例指针。可以通过传入各种HTTPServerOption函数 来自定义服务器,这些函数将根据这些选项封装的功能修改服务器的配置。这种模式被称为"函数选项模式", 它允许灵活且可读的服务器配置,而不需要一个可能很长的参数列表。
参数:
- opts: 一个可变的HTTPServerOption函数数组。每个函数都被应用于HTTPServer实例,并可以 设置或修改诸如中间件、日志记录、服务器地址、超时等配置。
InitHTTPServer函数按以下步骤操作:
- 使用一些初始默认设置创建一个新的HTTPServer实例。 a. 为服务器初始化一个router来管理传入请求的路由。 b. 设置一个默认的日志记录函数,将消息打印到标准输出,可通过选项覆盖。
- 遍历每个提供的HTTPServerOption,将其应用于服务器实例。这些选项是接受*HTTPServer参数 并修改其属性的函数,从而根据应用程序的特定需求定制服务器。
- 应用所有选项后,函数返回定制的HTTPServer实例,准备启动并开始处理传入的HTTP请求。
这个初始化函数抽象了服务器设置的复杂性,允许开发者仅指定与其应用程序相关的选项, 从而使服务器初始化代码更加清晰和可维护。
func (*HTTPServer) CONNECT ¶ added in v0.0.10
func (s *HTTPServer) CONNECT(path string, handleFunc HandleFunc, ms ...Middleware)
CONNECT 注册一个新的路由及其关联的处理函数,用于处理HTTP CONNECT请求。 HTTP CONNECT方法主要用于建立到由给定URI标识的服务器的隧道。
参数:
- path string: 服务器将监听传入CONNECT请求的端点或路由模式。这可能包括 参数占位符,可用于在请求处理期间从URL提取值。
- handleFunc: 响应对给定路径的CONNECT请求而调用的回调函数。此函数通过 *Context访问请求和响应,提供实现隧道行为或CONNECT请求上预期的 其他自定义逻辑所需的工具。
- ms: 一个可变的Middleware函数切片,在路由匹配时,这些函数将按传入顺序 在处理函数之前执行。
使用示例:
s.Connect("/proxy", func(ctx *Context) {
// 建立代理连接的逻辑。
})
注意: 使用`http.MethodConnect`确保只有HTTP CONNECT请求匹配到此处理程序, 便于为这些专门的请求类型提供适当的处理逻辑,这些请求类型与标准的 GET、POST、PUT等方法不同。
func (*HTTPServer) CacheStats ¶ added in v0.1.18
CacheStats 返回缓存统计信息
func (*HTTPServer) DELETE ¶ added in v0.0.10
func (s *HTTPServer) DELETE(path string, handleFunc HandleFunc, ms ...Middleware)
DELETE 注册一个新的路由及其关联的处理函数,用于HTTP DELETE请求。 此方法用于删除由URI标识的资源。
参数:
- path string: 服务器将监听传入DELETE请求的URL模式。 此参数定义了当DELETE请求匹配路径时将调用处理程序的端点。
- handleFunc: 当对注册的路径发出DELETE请求时调用的函数。此函数应包含 处理资源删除的逻辑,并提供*Context对象与请求和响应数据交互。
- ms: 一个可变的Middleware函数切片,在路由匹配时,这些函数将按传入顺序 在处理函数之前执行。
使用示例:
s.Delete("/users/{id}", func(ctx *Context) {
// 删除给定ID的用户资源的处理逻辑。
})
注意: 在调用registerRoute时使用`http.MethodDelete`将此处理程序限制为仅响应 DELETE请求,提供了一种定义服务器如何处理删除的方式。
func (*HTTPServer) DisableCache ¶ added in v0.1.18
func (r *HTTPServer) DisableCache()
DisableCache 禁用路由缓存
func (*HTTPServer) DisableRouteStats ¶ added in v0.1.19
func (s *HTTPServer) DisableRouteStats()
DisableRouteStats 禁用路由统计
func (*HTTPServer) DisableStats ¶ added in v0.1.19
func (r *HTTPServer) DisableStats()
DisableStats 禁用路由统计
func (*HTTPServer) EnableCache ¶ added in v0.1.18
func (r *HTTPServer) EnableCache(maxSize int)
EnableCache 启用路由缓存
func (*HTTPServer) EnableRouteStats ¶ added in v0.1.19
func (s *HTTPServer) EnableRouteStats()
EnableRouteStats 启用路由统计
func (*HTTPServer) EnableStats ¶ added in v0.1.19
func (r *HTTPServer) EnableStats()
EnableStats 启用路由统计
func (*HTTPServer) GET ¶ added in v0.0.10
func (s *HTTPServer) GET(path string, handleFunc HandleFunc, ms ...Middleware)
GET 注册一个带有关联处理函数的新路由,用于HTTP GET请求。 此方法主要用于从服务器检索数据。
参数:
- path string: 用于匹配传入GET请求的URL模式。当到达匹配此模式的GET请求时, 关联的处理函数将被执行。
- handleFunc: 当接收到匹配路径的请求时要调用的函数。处理函数被定义为 只接受一个*Context参数,通过它可以访问请求数据并发送响应。
- ms: 一个可变的Middleware函数切片,在路由匹配时,这些函数将按传入顺序 在处理函数之前执行。
使用示例:
s.Get("/home", func(ctx *Context) {
// 接收到HTTP GET请求时处理`/home`路径的处理程序逻辑
})
注意: 该方法内部调用registerRoute来将路由添加到服务器的路由表中, 将方法指定为`http.MethodGet`,这确保只有GET请求会被提供的处理程序处理。
func (*HTTPServer) GetAllRouteStats ¶ added in v0.1.19
func (s *HTTPServer) GetAllRouteStats() map[string]map[string]interface{}
GetAllRouteStats 获取所有路由的统计信息
func (*HTTPServer) GetRouteStats ¶ added in v0.1.19
func (s *HTTPServer) GetRouteStats(route string) (map[string]interface{}, bool)
GetRouteStats 获取指定路由的统计信息
func (*HTTPServer) Group ¶ added in v0.0.14
func (r *HTTPServer) Group(prefix string, ms ...Middleware) *routerGroup
Group 创建并返回一个附加到被调用路由器上的新routerGroup。 该方法通过检查前缀是否以正斜杠开始且不以正斜杠结束(除非是根组"/")来确保提供的前缀符合格式要求。 如果前缀无效,此方法会panic,以防止路由器配置错误。
参数:
- prefix: 新路由组的路径前缀。它应该以正斜杠开始, 除了根组外,不应以正斜杠结束。
- ms: 零个或多个中间件函数,这些函数将应用于创建的routerGroup内的每个路由。
返回: *routerGroup: 指向新创建的routerGroup的指针,带有给定的前缀和中间件。
Panic: 如果'prefix'不以'/'开始,或者如果'prefix'以'/'结束 (除非'prefix'恰好是"/"),此方法将会panic。
使用示例: r := &router{} // 假设路由器已初始化 group := r.Group("/api", loggingMiddleware, authMiddleware)
func (*HTTPServer) HEAD ¶ added in v0.0.10
func (s *HTTPServer) HEAD(path string, handleFunc HandleFunc, ms ...Middleware)
HEAD 注册一个新的路由及其关联的处理函数,用于HTTP HEAD请求。 此方法用于处理客户端只对响应头感兴趣而不需要实际响应体的请求, 这是HTTP HEAD请求的典型行为。
参数:
- path string: 路由将响应的路径模式。当收到对此模式的HEAD请求时, 注册的处理函数将被执行。
- handleFunc: 与提供的路径模式关联的处理函数。此函数将使用包含请求信息 和构建响应机制的*Context参数调用。
- ms: 一个可变的Middleware函数切片,在路由匹配时,这些函数将按传入顺序 在处理函数之前执行。
使用示例:
s.Head("/resource", func(ctx *Context) {
// 为'/resource'路径返回响应头的处理逻辑,
// 而不返回实际的响应体。
})
注意: 该方法使用registerRoute内部函数将路由添加到服务器的路由表中, 专门针对HEAD HTTP方法,这确保只有HEAD请求才会触发提供的处理函数的执行。
func (*HTTPServer) OPTIONS ¶ added in v0.0.10
func (s *HTTPServer) OPTIONS(path string, handleFunc HandleFunc, ms ...Middleware)
OPTIONS 注册一个新的路由及其关联的处理函数,用于HTTP OPTIONS请求。 HTTP OPTIONS方法用于描述目标资源的通信选项。
参数:
- path string: 服务器将匹配传入OPTIONS请求的URL模式。 定义端点允许客户端找出在给定URL或服务器上支持哪些方法和操作。
- handleFunc: 收到OPTIONS请求时要执行的函数。它通常提供关于 特定URL端点可用的HTTP方法的信息。handleFunc提供*Context对象, 以促进与HTTP请求和响应的交互。
- ms: 一个可变的Middleware函数切片,在路由匹配时,这些函数将按传入顺序 在处理函数之前执行。
使用示例:
s.Options("/articles/{id}", func(ctx *Context) {
// 处理逻辑,指示文章资源上支持的方法如GET、POST、PUT等。
})
注意: 由于使用了`http.MethodOptions`,此注册只影响OPTIONS请求。服务器上实现此方法是标准做法, 以便向客户端通知服务器能够处理的方法和内容类型,从而帮助客户端决定进一步的操作。
func (*HTTPServer) PATCH ¶ added in v0.0.10
func (s *HTTPServer) PATCH(path string, handleFunc HandleFunc, ms ...Middleware)
PATCH 注册一个新的路由及其关联的处理函数,用于HTTP PATCH请求。 此方法通常用于对现有资源进行部分更新。
参数:
- path string: 服务器将匹配传入PATCH请求的URL模式。 路径可以包含将从URL提取并传递给处理程序的变量。
- handleFunc: 当服务器在指定路径接收到PATCH请求时执行的函数。 此函数提供了*Context对象,使其能够访问请求信息和响应功能。
- ms: 一个可变的Middleware函数切片,在路由匹配时,这些函数将按传入顺序 在处理函数之前执行。
使用示例:
s.Patch("/profile/{id}", func(ctx *Context) {
// 基于URL中的ID对配置文件应用部分更新的处理逻辑。
})
注意: 使用`http.MethodPatch`常量注册路由确保只有PATCH请求由提供的函数处理。 PATCH方法通常用于对资源应用部分更新,而此函数是您定义服务器如何处理此类请求的地方。
func (*HTTPServer) POST ¶ added in v0.0.10
func (s *HTTPServer) POST(path string, handleFunc HandleFunc, ms ...Middleware)
POST 注册一个新的路由及其关联的处理函数,用于处理HTTP POST请求。 此方法用于应接受发送到服务器的数据的路由,通常是用于创建或更新资源。
参数:
- path string: 用于匹配传入POST请求的URL模式。它定义了处理函数将在 传入POST请求时被调用的端点。
- handleFunc: 当对指定路径发出POST请求时要执行的函数。它接收一个 *Context对象,该对象包含请求信息并提供向客户端写回响应的方法。
- ms: 一个可变的Middleware函数切片,在路由匹配时,这些函数将按传入顺序 在处理函数之前执行。
使用示例:
s.Post("/submit", func(ctx *Context) {
// 处理对`/submit`路径的POST请求的逻辑。
})
注意: 该方法委托给registerRoute,内部将HTTP方法设置为`http.MethodPost`。 这确保只有匹配指定路径的POST请求才会调用注册的处理程序。
func (*HTTPServer) PUT ¶ added in v0.0.10
func (s *HTTPServer) PUT(path string, handleFunc HandleFunc, ms ...Middleware)
PUT 注册一个新的路由及其关联的处理函数,用于处理HTTP PUT请求。 此方法通常用于更新现有资源或在特定URL创建新资源。
参数:
- path string: 服务器应监听PUT请求的URL模式。此模式可能包括URL的动态段的占位符, 这些占位符可用于向处理函数传递变量。
- handleFunc: 当对指定路径发出PUT请求时将调用的回调函数。该函数接受 一个*Context参数,该参数提供对请求数据和响应编写器的访问。
- ms: 一个可变的Middleware函数切片,在路由匹配时,这些函数将按传入顺序 在处理函数之前执行。
使用示例:
s.Put("/items/{id}", func(ctx *Context) {
// 使用PUT请求更新具有特定ID的项目的处理逻辑。
})
注意: 通过调用registerRoute并指定`http.MethodPut`,此方法确保处理程序 专门与PUT请求相关联。如果对匹配的路径发出PUT请求,将执行相应的处理函数。
func (*HTTPServer) ResetRouteStats ¶ added in v0.1.19
func (s *HTTPServer) ResetRouteStats()
ResetRouteStats 重置路由统计信息
func (*HTTPServer) ServeHTTP ¶
func (s *HTTPServer) ServeHTTP(writer http.ResponseWriter, request *http.Request)
ServeHTTP 是处理HTTP请求的主要入口点。
func (*HTTPServer) Shutdown ¶ added in v0.1.19
func (s *HTTPServer) Shutdown(ctx context.Context) error
Shutdown 优雅关闭服务器,等待现有请求完成
func (*HTTPServer) Start ¶
func (s *HTTPServer) Start(addr string) error
Start 启动HTTP服务器监听指定地址。它在给定地址上设置TCP网络监听器, 然后启动HTTP服务器以使用此监听器接受和处理传入请求。如果创建网络监听器 或启动服务器有问题,它会返回一个错误。
参数:
- addr: 一个字符串,指定服务器要监听的TCP地址。这通常包括主机名或IP, 后跟冒号和端口号(例如,"localhost:8080"或":80")。如果只指定带前导冒号的 端口号,服务器将在给定端口上的所有可用IP地址上监听。
Start函数按以下方式运行:
- 以"tcp"作为网络类型和提供的地址调用net.Listen。这尝试创建一个可以 在指定地址上接受传入TCP连接的监听器。
- 如果net.Listen返回错误,它会立即返回给调用者,表明无法创建监听器 (可能是由于无效地址、无法绑定到端口等)。
- 如果监听器成功创建,该函数然后以监听器和服务器本身作为参数调用http.Serve。 这启动HTTP服务器,它开始监听和处理请求。服务器将使用HTTPServer的ServeHTTP方法 处理每个请求。
- 如果http.Serve遇到错误,它也将返回给调用者。当服务器运行时遇到意外问题时 可能会发生这种情况,比如无法接受连接。
Start方法是一个阻塞调用。一旦调用,它将继续运行,服务传入的HTTP请求, 直到遇到错误或服务器被手动停止。
func (*HTTPServer) StartHTTP3 ¶ added in v0.1.21
func (s *HTTPServer) StartHTTP3(addr, certFile, keyFile string) error
StartHTTP3 启动支持HTTP/3的服务器
func (*HTTPServer) StartTLS ¶ added in v0.1.19
func (s *HTTPServer) StartTLS(addr, certFile, keyFile string) error
StartTLS 启动HTTPS服务器
func (*HTTPServer) UseForAll ¶ added in v0.0.5
func (s *HTTPServer) UseForAll(path string, mdls ...Middleware)
UseForAll 为指定路径注册所有HTTP方法的中间件
func (*HTTPServer) UseRoute ¶
func (s *HTTPServer) UseRoute(method string, path string, mils ...Middleware)
UseRoute 将一个新的路由与指定的HTTP方法和路径关联到服务器的路由系统中。 此外,它允许链接可以在请求到达最终处理函数之前拦截并修改请求或响应, 或执行特定操作如日志记录、身份验证等的中间件函数。
参数:
- method string: 要为其注册路由的HTTP方法(例如,GET,POST,PUT,DELETE)。
- path string: 与传入请求的URL匹配的路径模式。
- mils ...Middleware: 一个可变参数,允许传递任意数量的中间件函数。 这些函数按照提供的顺序执行,在最终处理程序之前。
用法: 注册路由时,可以指定HTTP方法和路径,然后是你希望应用的一系列中间件。 如果在路由注册时没有提供最终处理程序,则以后必须附加一个,路由才能正常工作。
使用示例:
s.UseRoute("GET", "/articles", AuthMiddleware, LogMiddleware)
这里,`AuthMiddleware`将用于认证请求,`LogMiddleware`将记录请求详情。 随后需要添加一个路由处理程序来处理`/articles`路径的GET请求。
注意: 此方法用于初始路由设置,必须与处理程序注册组合以创建完整、功能性的路由。 如果稍后没有附加处理程序,路由将不会有任何效果。
type HTTPServerOption ¶
type HTTPServerOption func(server *HTTPServer) // 用于配置HTTPServer的函数选项
HTTPServerOption定义了一个用于应用配置选项到HTTPServer的函数类型。
每个HTTPServerOption是一个接受指向HTTPServer的指针并根据某些配置逻辑修改它的函数。 这种模式,通常称为"函数选项模式",允许在构建HTTPServer实例时以灵活、清晰且安全的方式进行配置。 它使程序员能够在创建新服务器实例或调整其设置时以声明式方式链接多个配置选项。
用法: 开发者可以定义自定义HTTPServerOption函数,这些函数设置HTTPServer的各个字段或初始化其某些部分。 然后可以将这些选项传递给一个构造函数,该函数将它们应用于服务器实例。
示例:
func WithTemplateEngine(engine TemplateEngine) HTTPServerOption {
return func(server *HTTPServer) {
server.templateEngine = engine
}
}
func WithMiddleware(middleware ...Middleware) HTTPServerOption {
return func(server *HTTPServer) {
server.mils = append(server.mils, middleware...)
}
}
// 初始化新的HTTPServer:
srv := NewHTTPServer(
WithTemplateEngine(myTemplateEngine),
WithMiddleware(AuthMiddleware, LoggingMiddleware),
)
func ServerWithTemplateEngine ¶
func ServerWithTemplateEngine(templateEngine TemplateEngine) HTTPServerOption
ServerWithTemplateEngine 是一个配置函数,返回一个HTTPServerOption。 这个选项用于为HTTPServer设置特定的模板引擎,然后可以用来为客户端渲染HTML模板。 当你的服务器需要提供从模板生成的动态网页时,这个功能很有用。
模板引擎是一个接口或一组功能,它处理模板及给定数据,并生成HTTP服务器可以发送到 客户端网页浏览器的HTML输出。
使用示例:
server := NewHTTPServer(
ServerWithTemplateEngine(myTemplateEngine),
)
参数:
- templateEngine : 要设置到HTTPServer上的模板引擎。 此参数指定服务器将用于渲染模板的模板引擎的具体实现。
返回:
- HTTPServerOption : 一个用指定的模板引擎配置服务器的函数。 当作为服务器的选项应用时,它将'templateEngine'分配给服务器的 内部字段,以供以后使用。
func WithServerConfig ¶ added in v0.1.19
func WithServerConfig(config ServerConfig) HTTPServerOption
WithServerConfig 设置HTTP服务器配置
type HandleFunc ¶
type HandleFunc func(ctx *Context) // 框架内请求处理函数的类型签名
HandleFunc 定义了Web框架特定的HTTP请求处理函数的函数签名。
此类型表示一个函数,它接受一个指向Context对象的指针作为参数,并且不返回任何值。 Context对象通常封装了有关当前HTTP请求的所有信息,包括请求本身、响应写入器、 路径参数、查询参数以及处理请求所需的任何其他元数据或工具。
用法: HandleFunc旨在用作特定路由的回调函数,以处理传入的HTTP请求。 每个路由都将有一个关联的HandleFunc,当路由匹配时将执行该HandleFunc。
示例:
func HelloWorldHandler(ctx *Context) {
ctx.ResponseWriter.Write([]byte("Hello, World!"))
}
// 将处理程序注册到路由:
server.registerRoute("GET", "/hello", HelloWorldHandler)
type LogRotateConfig ¶ added in v0.1.19
type LogRotateConfig struct {
Filename string
MaxSize int // 单个文件的最大尺寸,MB
MaxAge int // 保留日志的最大天数
MaxBackups int // 保留的最大旧日志文件数
LocalTime bool // 使用本地时间
Compress bool // 是否压缩旧日志
}
日志文件旋转配置
type Logger ¶ added in v0.0.13
type Logger interface {
Debug(msg string, args ...any)
Info(msg string, args ...any)
Warn(msg string, args ...any)
Error(msg string, args ...any)
Fatalln(msg string, args ...any)
WithField(key string, value any) Logger
SetLevel(level LogLevel)
GetLevel() LogLevel
SetOutput(w io.Writer)
}
Logger is an interface that specifies logging functionality. 扩展Logger接口,提供更多日志级别
func GetDefaultLogger ¶ added in v0.1.19
func GetDefaultLogger() Logger
GetDefaultLogger 返回当前默认的日志记录器
type MemStats ¶ added in v0.1.27
type MemStats struct {
// 常规内存统计信息
Alloc uint64 // 当前已分配的内存字节数
TotalAlloc uint64 // 累计分配的总内存字节数
Sys uint64 // 从系统获取的总内存字节数
NumGC uint32 // GC运行次数
PauseTotalNs uint64 // GC暂停总时间
LastGC time.Time // 最后一次GC的时间
// Goroutine信息
NumGoroutine int // 当前goroutine数量
// 内存使用趋势
PrevAlloc uint64 // 上次检查时的内存使用量
AllocGrowth int64 // 内存使用增长量(可为负数)
GrowthRate float64 // 内存增长率
// 采样时间
SampleTime time.Time // 采样时间点
}
MemStats 保存内存统计信息
type MemoryMonitor ¶ added in v0.1.27
type MemoryMonitor struct {
// contains filtered or unexported fields
}
MemoryMonitor 是一个内存使用监控器
func NewMemoryMonitor ¶ added in v0.1.27
func NewMemoryMonitor(interval time.Duration, maxSamples int) *MemoryMonitor
NewMemoryMonitor 创建一个新的内存监控器
func (*MemoryMonitor) AddAlertCallback ¶ added in v0.1.27
func (m *MemoryMonitor) AddAlertCallback(callback AlertCallback)
AddAlertCallback 添加告警回调函数
func (*MemoryMonitor) GetCurrentStats ¶ added in v0.1.27
func (m *MemoryMonitor) GetCurrentStats() MemStats
GetCurrentStats 获取当前内存统计信息
func (*MemoryMonitor) GetMemoryUsageReport ¶ added in v0.1.27
func (m *MemoryMonitor) GetMemoryUsageReport() map[string]interface{}
GetMemoryUsageReport 获取内存使用报告
func (*MemoryMonitor) GetSamples ¶ added in v0.1.27
func (m *MemoryMonitor) GetSamples() []MemStats
GetSamples 获取历史采样数据
func (*MemoryMonitor) SetAlertThreshold ¶ added in v0.1.27
func (m *MemoryMonitor) SetAlertThreshold(threshold float64)
SetAlertThreshold 设置告警阈值
type Middleware ¶
type Middleware func(next HandleFunc) HandleFunc
Middleware 表示Go中的一个函数类型,定义了中间件函数的结构。 在Web服务器或其他请求处理应用程序的上下文中,中间件用于在请求到达最终请求处理程序之前处理请求, 允许进行预处理,如认证、日志记录或在请求的主要处理之前或之后应执行的任何其他操作。
该类型被定义为一个函数,它接受一个HandleFunc作为参数(通常称为'next')并返回另一个HandleFunc。 括号内的HandleFunc是链中中间件将调用的下一个函数,而返回的HandleFunc是该函数的修改或"包装"版本。
典型的中间件将执行一些操作,然后调用'next'将控制权传递给后续的中间件或最终处理程序, 可能在'next'返回后执行一些操作,最后返回'next'的结果。通过这样做,它形成了一个请求流经的中间件函数链。
Middleware类型设计得灵活且可组合,使得有序的中间件函数序列的构建变得简单和模块化。
参数:
- 'next': 要用额外行为包装的HandleFunc。这是通常会处理请求的函数或者是链中的下一个中间件。
返回值: - 一个HandleFunc,表示将中间件的行为添加到'next'函数后的结果。
用法:
- 中间件函数通常与路由器或服务器一起使用,以处理HTTP请求。
- 它们被链接在一起,使得请求在最终被主处理函数处理之前通过一系列中间件。
注意事项:
- 在设计中间件时,应确保不会无意中跳过必要的'next'处理程序。 除非是有意的(例如,阻止未授权请求的授权中间件),中间件通常应该调用'next'。
- 小心处理中间件中的错误。决定是在中间件本身内处理和记录错误,还是将它们传递给其他机制处理。
- 中间件函数应避免更改请求,除非这是其明确职责的一部分, 例如设置上下文值或修改与中间件特定功能相关的头部。
type PathTrie ¶ added in v0.1.18
type PathTrie struct {
// contains filtered or unexported fields
}
PathTrie 是一个高性能的路由前缀树实现
func (*PathTrie) Add ¶ added in v0.1.18
func (t *PathTrie) Add(method, path string, handler HandleFunc, middleware ...Middleware)
Add 向前缀树添加路由
func (*PathTrie) CacheStats ¶ added in v0.1.18
CacheStats 返回缓存统计信息
func (*PathTrie) DisableCache ¶ added in v0.1.18
func (t *PathTrie) DisableCache()
DisableCache 禁用缓存
func (*PathTrie) EnableCache ¶ added in v0.1.18
EnableCache 启用缓存
type Server ¶
type Server interface {
http.Handler // 继承的ServeHTTP方法用于处理请求
Start(addr string) error // 方法用于在给定地址上启动服务器
// contains filtered or unexported methods
}
Server定义了一个可以处理请求并在指定地址上启动的HTTP服务器接口。 它扩展了net/http包的http.Handler接口,该接口要求实现ServeHTTP方法来处理HTTP请求。 除了处理HTTP请求外,服务器还可以注册带有关联处理程序和中间件的路由,并在网络地址上启动。
方法:
Start(addr string) error: 在指定的网络地址(addr)上启动服务器。 如果服务器启动失败,它会返回一个错误。
registerRoute(method string, path string, handleFunc, mils ...Middleware): 注册 一个带有特定HTTP方法和路径的新路由。如果提供了handleFunc,它将成为处理匹配请求的 主要函数;mils代表在路由匹配时将在handleFunc之前处理的可变中间件函数。
注意:
- registerRoute方法通常不对外暴露,它主要供Server接口的实现内部使用。 实现应确保正确注册路由并在此方法中正确应用中间件。
示例: Server接口的实现可以管理自己的路由表和中间件栈, 允许模块化和可测试的服务器设计。通常在应用程序中的使用方式如下:
func main() {
srv := NewMyHTTPServer() // MyHTTPServer实现了Server接口
srv.registerRoute("GET", "/", HomePageHandler, LoggingMiddleware)
err := srv.Start(":8080")
if err != nil {
log.Fatalf("启动服务器失败: %v", err)
}
}
type ServerConfig ¶ added in v0.1.19
type ServerConfig struct {
ReadTimeout time.Duration // 读取整个请求的超时时间
WriteTimeout time.Duration // 写入响应的超时时间
IdleTimeout time.Duration // 连接空闲超时时间
ReadHeaderTimeout time.Duration // 读取请求头的超时时间
MaxHeaderBytes int // 请求头的最大字节数
RequestTimeout time.Duration // 单个请求处理的最大时间
// HTTP/2和HTTP/3支持
EnableHTTP2 bool // 是否启用HTTP/2
EnableHTTP3 bool // 是否启用HTTP/3
HTTP3IdleTimeout time.Duration // HTTP/3连接空闲超时时间
QuicMaxIncomingStreams int // QUIC最大并发流数量
}
ServerConfig 定义HTTP服务器的配置选项
func DefaultServerConfig ¶ added in v0.1.19
func DefaultServerConfig() ServerConfig
DefaultServerConfig 返回默认的服务器配置
type StaticResourceHandler ¶
type StaticResourceHandler struct {
// contains filtered or unexported fields
}
StaticResourceHandler is a structure used for serving static files such as images, CSS, or JavaScript files from a defined directory within a web server. It's designed to efficiently handle requests for static content by caching frequently requested resources, understanding content types based on file extensions, and allowing limits on the size of files served.
Fields:
- dir string: The root directory from where the static resources will be served. This should be an absolute path to ensure correct file resolution. When a request comes in for a static resource, the handler will use this directory to look up and serve the files.
- cache *lru.Cache: An LRU (Least Recently Used) cache used to store and retrieve the most recently accessed static files quickly. The caching mechanism improves the performance of the web server by reducing the number of disk reads. The 'lru.Cache' refers to an in-memory key-value store where the key is typically the file path or name, and the value is the file's content.
- extContentTypeMap map[string]string: A map associating file extensions with their corresponding MIME content type. This mapping allows the server to set the appropriate 'Content-Type' header in HTTP responses based on the requested file's extension. For example, it might map ".css" to "text/css" and ".png" to "image/png".
- maxSize int: The maximum size of a file, in bytes, that the handler will serve. Requests for files larger than this size will result in an error, preventing the server from consuming excessive resources when serving large files. This is a safeguard to help maintain server performance and stability.
The StaticResourceHandler struct requires careful initialization to ensure it has access to the correct directory and that the cache and content type map are adequately configured. It can be used in standalone mode or as part of an HTTP server, integrating with the server's request handling mechanism to serve the static files when requested.
Once appropriately configured, the StaticResourceHandler provides a robust and efficient way to handle requests for static resources, enabling you to optimize the delivery of these files as part of your web application's overall performance strategy.
func InitStaticResourceHandler ¶
func InitStaticResourceHandler(dir string, opts ...StaticResourceHandlerOption) (*StaticResourceHandler, error)
InitStaticResourceHandler initializes and returns a pointer to a StaticResourceHandler with the provided directory path and applies any given configuration options. The function also establishes an LRU (Least Recently Used) cache with a default maximum capacity to optimize the serving of static files. This function centralizes the setup logic for creating a StaticResourceHandler, ensuring that the handler is properly initialized and configured before use.
Parameters:
- dir string: The absolute directory path where the static resources are located. This will be the root directory from which the server will serve static files.
- opts ...StaticResourceHandlerOption: A variadic slice of functional options used to customize the configuration of the StaticResourceHandler. These options are applied in the order they're received, allowing the caller to override default values and behavior.
Return Values:
- *StaticResourceHandler: A pointer to the newly-created configured StaticResourceHandler ready to serve static files.
- error: An error that may have occurred during the creation or configuration of the StaticResourceHandler. If the error is not nil, it usually indicates a problem with setting up the internal LRU cache.
Internal Initialization Steps:
- The function creates an LRU cache with a default size of 1000 cache entries. If the cache cannot be created, the function immediately returns nil and the error.
- A StaticResourceHandler struct instance is instantiated with the given directory path and the newly created LRU cache.
- Default file size limit for serving files is set to 1 megabyte (1024 * 1024 bytes).
- A default extension to content type mapping is established for common file formats to ensure correct 'Content-Type' headers in HTTP responses.
- The function then iterates through each provided configuration option, applying it to the newly created StaticResourceHandler instance. This allows customization such as changing the maximum cache size or adding new file type mappings.
- The fully configured StaticResourceHandler pointer is then returned for usage in the server.
Example Usage: handler, err := InitStaticResourceHandler("/path/to/static/resources",
SetMaxSize(500 * 1024), // 500 KB as the max file size
AddFileTypeMapping("svg", "image/svg+xml"), // Add SVG MIME type mapping
)
if err != nil {
log.Fatalf("Failed to initialize static resource handler: %v", err)
}
// Now handler can be used to serve static resources with the specified configurations.
func (*StaticResourceHandler) Handle ¶
func (s *StaticResourceHandler) Handle(ctx *Context)
Handle takes a Context pointer and serves static files based on the request's path. It attempts to retrieve and serve the requested file, handling various error scenarios gracefully. It sets appropriate HTTP response status codes and headers, leveraging an LRU cache for performance optimization when possible.
The method logic is as follows:
- It extracts the requested 'file' from the context's PathValue.
- If there's an error in retrieving the file (e.g., malformed request path), it sends a 400 Bad Request status and a "Request path error" message.
- If the file can be retrieved, it constructs a full file path using the provided directory path and the file's name.
- The file extension is extracted to determine the correct content type from the handler's extension to MIME type mapping (extContentTypeMap).
- If the file's data is found in the cache, it uses this data to set the response headers and body, sending a 200 OK status code.
- If not cached, it reads the file from disk using os.ReadFile.
- If there's an error reading the file (e.g., file not found, permissions issue), it sets a 500 Internal Server Error status code and a "Server error" message.
- It checks if the file size is within the allowed maximum size (s.maxSize). If it is, the function adds the file's data to the cache.
- Lastly, it sets the correct "Content-Type" and "Content-Length" headers and sends the file data with a 200 OK status.
Parameters:
- ctx *Context: A pointer to the Context object which contains information about the HTTP request and utilities for writing a response.
Note: This method should be used to handle routes that match static file requests. It automatically uses caching to improve performance, but it also ensures that the file size does not exceed a configured threshold before caching the data.
Example Usage: Assuming 'handler' is an instance of StaticResourceHandler with a configured directory and cache, the Handle method would be attached to a web server route like so:
http.Handle("/static/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := NewContext(r, w)
handler.Handle(ctx)
}))
This specifies that all requests to '/static/' should be handled by the Handle method of 'handler', which will serve the files as static resources.
type StaticResourceHandlerOption ¶
type StaticResourceHandlerOption func(handler *StaticResourceHandler)
StaticResourceHandlerOption is a type for a function which acts as an option or a modifier for instances of StaticResourceHandler. This type enables a flexible configuration pattern commonly known as "functional options", which allows the customization of various aspects of a StaticResourceHandler instance at the time of its creation or initialization.
Functional options are a way to cleanly and idiomatically pass configuration data to struct instances or objects in Go. They provide several benefits over traditional configuration approaches such as configuration structs or variadic parameters:
- Options are entirely optional, allowing for a more succinct API where defaults can be used unless explicitly overridden.
- They provide extensibility and forward-compatibility. As new options become necessary, they can be added without breaking existing clients or code.
- They allow for complex and interdependent properties to be set, which might be clunky or error-prone with other configuration mechanisms.
- They preserve the immutability of the object after creation, enabling a clearer, less error-prone API since clients are discouraged from modifying the object's properties directly after it has been created.
How StaticResourceHandlerOption is used: An option function takes a pointer to a StaticResourceHandler instance and modifies it directly. This function may set default values, modify settings, or provide additional functionality to the handler based on its implementation. During the construction or initialization of a StaticResourceHandler, one or more of these option functions can be passed, which will be applied to the handler instance to configure it according to the provided options.
Example Usage: Below is a simplified example of how one might define and use a StaticResourceHandlerOption function to configure a static resource handler for serving files from a particular directory.
func DirectoryOption(directory string) StaticResourceHandlerOption {
return func(handler *StaticResourceHandler) {
handler.Directory = directory
}
}
// When creating a new StaticResourceHandler, pass the option function to configure its directory. handler := NewStaticResourceHandler(
DirectoryOption("/path/to/static/resources"),
// ...other options could be passed here as well...
)
The StaticResourceHandler can now be used with its Directory correctly set to the specified path, and this pattern permits the combination of multiple options to achieve complex configurations in an expressive and maintainable way.
func StaticWithCache ¶
func StaticWithCache(c *lru.Cache) StaticResourceHandlerOption
StaticWithCache returns a StaticResourceHandlerOption that assigns a custom LRU (Least Recently Used) cache to a StaticResourceHandler. The provided *lru.Cache replaces the default cache, allowing for higher flexibility in how caching is configured for the static file handler. This is particularly useful for fine-tuning the cache size or sharing a cache instance among multiple handlers.
Parameters:
- c *lru.Cache: A pointer to the lru.Cache instance that should be used by the StaticResourceHandler. This parameter allows the user to specify the exact cache instance, including its size and eviction policies, which will be integrated into the static resource serving process.
Returns:
- StaticResourceHandlerOption: A closure function that accepts a *StaticResourceHandler as its parameter. When executed, this option function sets the StaticResourceHandler's internal cache pointer to the provided *lru.Cache instance.
This configuration option is valuable when performance optimization is needed or when different caching strategies are tested. It provides the ability to swap in a custom cache with a pre-defined configuration without altering the existing flow of the handler's initialization.
Example Usage: To use a previously configured lru.Cache with a capacity of 500 items in a new StaticResourceHandler, invoke StaticWithCache like this:
existingCache, _ := lru.New(500) // Create an lru.Cache with a capacity for 500 items. handler, err := InitStaticResourceHandler("/static", StaticWithCache(existingCache))
if err != nil {
// handle error
}
This allows the new StaticResourceHandler to utilize the existingCache for caching static files, providing a customized caching strategy as per the application's requirements.
Adopting a feature-rich cache can significantly reduce IO operations against the disk and improve the serving speed of static files, leading to better application performance and scalability. The option to set a custom cache is a direct way to control these aspects.
func StaticWithExtension ¶
func StaticWithExtension(extMap map[string]string) StaticResourceHandlerOption
StaticWithExtension returns a StaticResourceHandlerOption which extends or overrides the existing file extension to MIME type mappings in a StaticResourceHandler. The provided extMap parameter is a map of file extensions to their respective MIME types. This function is helpful when you need the StaticResourceHandler to recognize additional file types or modify existing associations.
Parameters:
- extMap map[string]string: This map represents the file extensions and their associated MIME types that should be recognized by the StaticResourceHandler. Keys in the map should be file extensions without the dot (e.g., "txt"), and the values should be the corresponding MIME types (e.g., "text/plain").
Returns:
- StaticResourceHandlerOption: A functional option that, when applied to a StaticResourceHandler, updates its 'extContentTypeMap' field to include the mappings from extMap. If an extension already exists in the handler's mapping, it will be overridden with the new MIME type provided in extMap.
This function offers a way to customize the content type determination process when serving static files. By specifying file extension to MIME type mappings, the server can set correct 'Content-Type' headers in HTTP responses. This is vital for browsers or clients to handle the received files appropriately.
Example Usage: To add or override mappings for ".svg" and ".json" files in a StaticResourceHandler, use StaticWithExtension like this:
customExtMap := map[string]string{
"svg": "image/svg+xml",
"json": "application/json",
}
handler, err := InitStaticResourceHandler("/static", StaticWithExtension(customExtMap))
if err != nil {
// handle error
}
The above code configures the handler to recognize ".svg" files with the MIME type "image/svg+xml" and ".json" files with "application/json". These mappings will be added to or replace any existing mappings for these extensions in the handler.
This level of customization aids in serving a broader range of file types or catering to specific client needs while ensuring that the server's responses are correctly understood by the client.
func StaticWithMaxFileSize ¶
func StaticWithMaxFileSize(maxSize int) StaticResourceHandlerOption
StaticWithMaxFileSize returns a StaticResourceHandlerOption which sets the maximum file size (in bytes) that a StaticResourceHandler is allowed to serve. The maxSize parameter specifies the size limit, and files exceeding this limit will not be served by the handler. This option function is part of a pattern allowing granular configuration of a StaticResourceHandler through functional options, which are applied when initializing the handler with the InitStaticResourceHandler function.
Parameters:
- maxSize int: The maximum size (in bytes) that the StaticResourceHandler will serve. This acts as a guard against serving excessively large static files, potentially consuming too much memory or bandwidth.
Returns:
- StaticResourceHandlerOption: A function closure that when called with a *StaticResourceHandler, will assign the specified maxSize to the handler's maxSize field.
The maxSize is an essential configuration as it helps to manage server resources efficiently and ensures the server does not get overloaded by requests for very large files. This is particularly useful when you expect that your server might be serving large files and wish to put an explicit cap on them.
Example Usage: To create a StaticResourceHandler that has a maximum serving file size of 500KB, you would use the StaticWithMaxFileSize option like so:
handler, err := InitStaticResourceHandler("/static", StaticWithMaxFileSize(500 * 1024))
if err != nil {
// handle error
}
When the above handler is used in a server, any request for a static file larger than 500KB will be denied or handled according to the server's implementation.
Using this function enables the developer to tailor the StaticResourceHandler's behavior to the specific requirements of their application or the resource constraints of their server environment.
type StdLogger ¶ added in v0.1.19
type StdLogger struct {
// contains filtered or unexported fields
}
StdLogger 是Logger接口的标准实现
func NewStdLogger ¶ added in v0.1.19
NewStdLogger 创建一个标准日志记录器
type TemplateEngine ¶
type TemplateEngine interface {
// Render takes the name of a template and the data object to be used in rendering, and returns the
// rendered template as a slice of bytes, or an error if the rendering could not be completed. This
// method abstracts the rendering logic, enabling different templating systems to be integrated into
// the application as needed.
Render(ctx context.Context, templateName string, data any) ([]byte, error)
}
TemplateEngine defines the contract for a template rendering system used to generate text output (such as HTML, XML, etc.) based on predefined templates and dynamic data. Such an engine typically supports a variety of operations related to template parsing, data binding, and the generation of rendered output. This interface abstracts these operations so that different implementations of templating engines can be used interchangeably within an application.
The interface includes a single method, Render, which must be implemented by any concrete type that purports to be a template engine. This method takes a template name and associated data and produces the rendered output as a slice of bytes, along with an error if the rendering process fails.
Render method parameters:
- ctx (context.Context): The context parameter allows the Render method to be aware of the broader context of the application, such as deadlines, cancellation signals, and other request-scoped values. It enables the rendering process to handle timeouts or cancellations as per the application's context.
- templateName (string): This is the identifier or the name of the template that needs to be rendered. The templating engine uses this name to look up and load the appropriate template file or content from an internal cache or the filesystem.
- data (any): The data parameter is an interface{} type, allowing any kind of Go value to be passed as the data context for the template. This data is then utilized by the template engine to dynamically populate placeholders within the template, enabling the generation of customized output based on the data provided.
Render method returns:
- []byte: When successful, Render returns the generated content as a byte slice, which can be used directly as output to a response writer or converted to a string for further processing.
- error: If any errors occur during the rendering of the template, Render returns an error detailing the issue encountered. This could be due to reasons like template parsing errors, missing data required to fill in the template, file system issues when accessing template files, etc.
Notes:
- Implementations of the TemplateEngine interface should ensure to handle any template-specific syntax and errors internally, providing a consistent and easy-to-use API for rendering content within an application.
- The flexibility of this interface allows for custom implementations that could include enhanced features like caching, internationalization support, and more.
type ZeroCopyResponse ¶ added in v0.1.27
type ZeroCopyResponse struct {
// contains filtered or unexported fields
}
ZeroCopyResponse 提供高效的零拷贝响应机制 这个结构体设计用于大文件传输场景,可以避免不必要的内存拷贝, 直接将文件内容从磁盘传输到网络连接
func NewZeroCopyResponse ¶ added in v0.1.27
func NewZeroCopyResponse(w http.ResponseWriter) *ZeroCopyResponse
NewZeroCopyResponse 创建一个新的零拷贝响应对象
func (*ZeroCopyResponse) Header ¶ added in v0.1.27
func (z *ZeroCopyResponse) Header() http.Header
Header 返回响应头
func (*ZeroCopyResponse) ServeFile ¶ added in v0.1.27
func (z *ZeroCopyResponse) ServeFile(filePath string) error
ServeFile 使用零拷贝技术提供文件服务 如果底层连接支持sendfile系统调用,将使用零拷贝方式 否则回退到标准http.ServeContent
func (*ZeroCopyResponse) Write ¶ added in v0.1.27
func (z *ZeroCopyResponse) Write(data []byte) (int, error)
Write 实现标准的Write接口
func (*ZeroCopyResponse) WriteHeader ¶ added in v0.1.27
func (z *ZeroCopyResponse) WriteHeader(statusCode int)
WriteHeader 写入状态码
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package apidoc 提供了API文档生成工具
|
Package apidoc 提供了API文档生成工具 |
|
Package config 提供统一的配置管理系统
|
Package config 提供统一的配置管理系统 |
|
internal
|
|
|
middlewares
|
|
|
cache
Package cache 提供了基于内存的HTTP响应缓存中间件
|
Package cache 提供了基于内存的HTTP响应缓存中间件 |
|
blocklist/example
command
|
|
|
id/example
command
|
|
|
report/example
command
|
|