Import path:
gitlab.soludian.com/soludian/fountain/libs/fnet/fhttp
fhttp
import "gitlab.soludian.com/soludian/fountain/libs/fnet/fhttp"Index
- Constants
- Variables
- func AddFiberConfigs(fiberConfigs ...fiber.Config) lib_3rd.Option[config]
- func AddTrustedCloudflareIPs(ips ...string) lib_3rd.Option[config]
- func BodyToContext(c fiber.Ctx) error
- func CreateCookie(ctx fiber.Ctx, domain, name, value string, expires time.Time, opts ...CookieOption)
- func DataToContext(reqParams ...ReqParam) func(c fiber.Ctx) error
- func DeleteCookie(ctx fiber.Ctx, domain, name string, opts ...CookieOption)
- func FormRequest(endpoint string, request any, encoder Encoder, authFn any) (*http.Request, error)
- func GRPCProxy(h any) fiber.Handler
- func GetQueryOffsetLimit(ctx fiber.Ctx, defaultLimit ...int) (offset, limit int)
- func HTTPWriteError(w http.ResponseWriter, err *froto.RpcError) error
- func HTTPWriteErrorWithExtend(w http.ResponseWriter, err *froto.RpcError, extend map[froto.Constructor]froto.ObjectInf) error
- func HTTPWriteSuccess(w http.ResponseWriter, v any) error
- func HTTPWriteSuccessEmptyContent(w http.ResponseWriter) error
- func HTTPWriteSuccessWithExtend(w http.ResponseWriter, data any, extend map[froto.Constructor]froto.ObjectInf) error
- func HasAuxiliaryServer() bool
- func HeaderToMetadataIncoming(c fiber.Ctx) error
- func HttpRequest[T any](client *http.Client, req *http.Request, response T) error
- func NewFErrorResponse(err *froto.RpcError) (string, *froto.RpcError)
- func ParamToBody(reqParams ...ReqParam) func(c fiber.Ctx) error
- func ParamToContext(reqParams ...ReqParam) func(c fiber.Ctx) error
- func QueryToBody(reqParams ...ReqParam) func(c fiber.Ctx) error
- func QueryToContext(reqParams ...ReqParam) func(c fiber.Ctx) error
- func StructToQueryString(v any) string
- func TrustedInternalIPs() []string
- func Validate(m any) *froto.RpcError
- func WithAccessInterceptorReqResFilter(filter string) lib_3rd.Option[config]
- func WithAddress(addr string) lib_3rd.Option[config]
- func WithBlockFallback(blockFallback func(fiber.Ctx) error) lib_3rd.Option[config]
- func WithCORSAllowCredentials(allow ...bool) lib_3rd.Option[config]
- func WithCORSAllowOrigins(origins ...string) lib_3rd.Option[config]
- func WithCacheExpiration(d time.Duration) lib_3rd.Option[config]
- func WithCacheStorageName(name string) lib_3rd.Option[config]
- func WithContextTimeout(timeout time.Duration) lib_3rd.Option[config]
- func WithDisableAccessInterceptor(disable ...bool) lib_3rd.Option[config]
- func WithDisableMetricInterceptor(disable ...bool) lib_3rd.Option[config]
- func WithDisableTraceInterceptor(disable ...bool) lib_3rd.Option[config]
- func WithEmbedFs(fs embed.FS) lib_3rd.Option[config]
- func WithEmbedPath(path string) lib_3rd.Option[config]
- func WithEnableAccessInterceptorReq(enable ...bool) lib_3rd.Option[config]
- func WithEnableAccessInterceptorRes(enable ...bool) lib_3rd.Option[config]
- func WithEnableCORS(enable ...bool) lib_3rd.Option[config]
- func WithEnableCache(enable ...bool) lib_3rd.Option[config]
- func WithEnableLimiter(enable ...bool) lib_3rd.Option[config]
- func WithEnableLocalMainIP(enable ...bool) lib_3rd.Option[config]
- func WithEnableMinify(enable ...bool) lib_3rd.Option[config]
- func WithEnableOPA(enable ...bool) lib_3rd.Option[config]
- func WithEnableResponseTime(enable ...bool) lib_3rd.Option[config]
- func WithEnableSentinel(enable ...bool) lib_3rd.Option[config]
- func WithEnableSouin(enable ...bool) lib_3rd.Option[config]
- func WithEnableTLS(enable ...bool) lib_3rd.Option[config]
- func WithEnableTrustedCustomHeader(enable ...bool) lib_3rd.Option[config]
- func WithEnableWAF(enable ...bool) lib_3rd.Option[config]
- func WithEnableWebsocketCheckOrigin(enable ...bool) lib_3rd.Option[config]
- func WithEnableWebsocketCompression(enable ...bool) lib_3rd.Option[config]
- func WithFiberConfigs(fiberConfigs ...fiber.Config) lib_3rd.Option[config]
- func WithIdempotencyKeyHeader(header string) lib_3rd.Option[config]
- func WithIdempotencyKeySecret(secret string) lib_3rd.Option[config]
- func WithIdempotencyLifetime(d time.Duration) lib_3rd.Option[config]
- func WithIdempotencyStorageName(name string) lib_3rd.Option[config]
- func WithLimiterExpiration(d time.Duration) lib_3rd.Option[config]
- func WithLimiterMax(max int) lib_3rd.Option[config]
- func WithLimiterStorageName(name string) lib_3rd.Option[config]
- func WithMetricCounter(counter metrics.Counter) lib_3rd.Option[config]
- func WithMetricHistogram(histogram metrics.Histogram) lib_3rd.Option[config]
- func WithMetricProviderName(name string) lib_3rd.Option[config]
- func WithMinifyMinifyJSON(enable ...bool) lib_3rd.Option[config]
- func WithMinifyMinifySVG(enable ...bool) lib_3rd.Option[config]
- func WithMinifyMinifyXML(enable ...bool) lib_3rd.Option[config]
- func WithName(name string) lib_3rd.Option[config]
- func WithNetworkProtocol(protocol string) lib_3rd.Option[config]
- func WithOPAPolicy(policy string) lib_3rd.Option[config]
- func WithOPAQuery(query string) lib_3rd.Option[config]
- func WithOPAURL(url string) lib_3rd.Option[config]
- func WithResourceExtract(resourceExtract func(fiber.Ctx) string) lib_3rd.Option[config]
- func WithServerHTTPTimeout(timeout time.Duration) lib_3rd.Option[config]
- func WithServerReadHeaderTimeout(timeout time.Duration) lib_3rd.Option[config]
- func WithServerReadTimeout(timeout time.Duration) lib_3rd.Option[config]
- func WithServerWriteTimeout(timeout time.Duration) lib_3rd.Option[config]
- func WithSlowLogThreshold(duration time.Duration) lib_3rd.Option[config]
- func WithSouinExcludedRegex(regex string) lib_3rd.Option[config]
- func WithSouinHandler(h middleware.SouinHandler) lib_3rd.Option[config]
- func WithSouinLogLevel(level string) lib_3rd.Option[config]
- func WithSouinTTL(d time.Duration) lib_3rd.Option[config]
- func WithTLSCertFile(path string) lib_3rd.Option[config]
- func WithTLSClientAuth(auth string) lib_3rd.Option[config]
- func WithTLSClientCAs(ca []string) lib_3rd.Option[config]
- func WithTLSKeyFile(path string) lib_3rd.Option[config]
- func WithTLSSessionCache(s tls.ClientSessionCache) lib_3rd.Option[config]
- func WithTrustedPlatform(platform string) lib_3rd.Option[config]
- func WithWAFBlock(block ...bool) lib_3rd.Option[config]
- func WithWAFDirectives(directives string) lib_3rd.Option[config]
- func WithWebsocketHandshakeTimeout(timeout time.Duration) lib_3rd.Option[config]
- func WithWebsocketReadBufferSize(size int) lib_3rd.Option[config]
- func WithWebsocketWriteBufferSize(size int) lib_3rd.Option[config]
- func WriteError(c fiber.Ctx, err *froto.RpcError) error
- func WriteErrorWithExtend(c fiber.Ctx, err *froto.RpcError, extend any) error
- func WriteErrorWithGRPCExtend(c fiber.Ctx, err *froto.RpcError, extend map[froto.Constructor]froto.ObjectInf) error
- func WriteNotImplementedError(c fiber.Ctx) error
- func WriteSuccess(c fiber.Ctx, v any) error
- func WriteSuccessEmptyContent(c fiber.Ctx) error
- func WriteSuccessWithExtend(c fiber.Ctx, data any, extend any) error
- func WriteSuccessWithGRPCExtend(c fiber.Ctx, data any, extend map[froto.Constructor]froto.ObjectInf) error
- func WriteSuccessWithPaging(c fiber.Ctx, v any, paging *Paging) error
- func WriteSuccessWithStatus(c fiber.Ctx, code int, v any) error
- func WriteWithErrorProcess(c fiber.Ctx, err error) error
- type CookieOption
- type Decoder
- type Encoder
- type FormAuthorization
- type Paging
- type ProbesFn
- type ReqParam
- type RequestAuthorization
- type Response
- type Server
- func GetAuxiliaryServer() *Server
- func (s *Server) CreateGovernanceServer()
- func (s *Server) CreateMetricsServer()
- func (s *Server) Destroy() (err error)
- func (s *Server) GetConfig() *config
- func (s *Server) GetName() string
- func (s *Server) GetPackageName() string
- func (s *Server) GracefulStop(ctx context.Context) error
- func (s *Server) InitHealthCheckPath(path string)
- func (s *Server) InitHealthCheckRoute(router fiber.Router)
- func (s *Server) RegisterReadyProbes(name string, probesFn ProbesFn) *Server
- func (s *Server) Serve() (err error)
- func (s *Server) Serving()
- func (s *Server) SetAccessInterceptorResCelProgram() *Server
Constants
const (
// HeaderAcceptEncoding ...
HeaderAcceptEncoding = "Accept-Encoding"
// HeaderContentType ...
HeaderContentType = "Content-Type"
// HeaderGRPCPROXYError ...
HeaderGRPCPROXYError = "GRPC-Proxy-Error"
// MIMEApplicationJSON ...
MIMEApplicationJSON = "application/json"
// MIMEApplicationJSONCharsetUTF8 ...
MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8
// MIMEApplicationProtobuf ...
MIMEApplicationProtobuf = "application/protobuf"
)const KDefaultCookieName = "cookie:fountain-session"const KDefaultCookieSecret = "b2tlbGEtZW5jcnlwdC1zZWNyZXQtY29va2llcy1rZXk="const (
KPackageName = "fhttp"
)Variables
CopyContextToFiberContext copies the values of context.Context to a fasthttp.RequestCtx
var CopyContextToFiberContext = adaptor.CopyContextToFiberContextvar DefaultHTTPClient = &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 50,
MaxConnsPerHost: 50,
},
}FiberApp wraps fiber app to net/http handler func
var FiberApp = adaptor.FiberAppFiberHandler wraps fiber handler to net/http handler
var FiberHandler = adaptor.FiberHandlerFiberHandlerFunc wraps fiber handler to net/http handler func
var FiberHandlerFunc = adaptor.FiberHandlerFuncGetClientIP lấy địa chỉ IP thực tế của client từ HTTP request context. Hàm này tuân theo thứ tự ưu tiên để xác định địa chỉ IP đáng tin cậy nhất:
- CF-Connecting-IP header (IP thực của client từ Cloudflare) 2. X-Forwarded-For header (lấy IP đầu tiên từ danh sách phân cách bằng dấu phẩy) 3. X-Real-IP header (thường được set bởi Nginx) 4. Fallback về ctx.IP() (phương thức phát hiện IP built-in của Fiber)
Tham số:
- ctx: fiber.Ctx - Context của Fiber chứa HTTP request
Trả về:
- string: Địa chỉ IP của client dưới dạng chuỗi
Lưu ý: Tất cả giá trị header đều được trim khoảng trắng trước khi trả về. Hàm này được thiết kế để hoạt động sau proxy và load balancer.
Usage:
app.Get("/api/user", func(c fiber.Ctx) error {
clientIP := fhttp.GetClientIP(c)
log.Printf("Request từ IP: %s", clientIP)
return c.JSON(fiber.Map{"client_ip": clientIP})
})
// Hoặc sử dụng hàm wrapper IP()
clientIP := fhttp.IP(c)
fmt.Printf("Client IP: %s", clientIP)var GetClientIP = middleware.GetClientIPvar GetFountainInstance = Lib.GetFountainInstancevar GetFountainManager = Lib.GetFountainManagerHTTPHandler wraps net/http handler to fiber handler
var HTTPHandler = adaptor.HTTPHandlerHTTPHandlerFunc wraps net/http handler func to fiber handler
var HTTPHandlerFunc = adaptor.HTTPHandlerFuncHTTPMiddleware wraps net/http middleware to fiber middleware
var HTTPMiddleware = adaptor.HTTPMiddlewareIP lấy địa chỉ IP thực tế của client từ HTTP request context. Hàm này tuân theo thứ tự ưu tiên để xác định địa chỉ IP đáng tin cậy nhất:
- CF-Connecting-IP header (IP thực của client từ Cloudflare) 2. X-Forwarded-For header (lấy IP đầu tiên từ danh sách phân cách bằng dấu phẩy) 3. X-Real-IP header (thường được set bởi Nginx) 4. Fallback về ctx.IP() (phương thức phát hiện IP built-in của Fiber)
Tham số:
- ctx: fiber.Ctx - Context của Fiber chứa HTTP request
Trả về:
- string: Địa chỉ IP của client dưới dạng chuỗi
Lưu ý: Tất cả giá trị header đều được trim khoảng trắng trước khi trả về. Hàm này được thiết kế để hoạt động sau proxy và load balancer.
Usage:
app.Get("/api/user", func(c fiber.Ctx) error {
clientIP := fhttp.GetClientIP(c)
log.Printf("Request từ IP: %s", clientIP)
return c.JSON(fiber.Map{"client_ip": clientIP})
})
// Hoặc sử dụng hàm wrapper IP()
clientIP := fhttp.IP(c)
fmt.Printf("Client IP: %s", clientIP)var IP = GetClientIPSử dụng khi config instance ở dạng key:value; Nếu config instance ở dạng key:array thì sử dụng hàm InstallFountainInstances Nếu config ở dạng key:array thì sẽ chỉ install config phần tử đầu tiên mà thôi
Install with config format <key>:<value>; eg: fhttp:<value>
Usage:
config.yaml:
fhttp:
name: default_name
...
code.go
fhttp.InstallFountainInstance()
fhttp.WithConfigKey("fhttp").InstallFountainInstance()var InstallFountainInstance = Lib.InstallFountainInstanceSử dụng khi config instance ở dạng key:array<value>; Sẽ luôn cố gắng khởi tạo kể cả khi config ở dạng key:value
Install with config format <key>:array<value>; eg: fhttp:array<value>
Usage:
config.yaml:
fhttp:
- name: default_name
...
code.go
fhttp.InstallFountainInstances()
fhttp.WithConfigKey("fhttp").InstallFountainInstances()var InstallFountainInstances = Lib.InstallFountainInstancesvar KDefaultServerName = env.GetFullAppService(KPackageName)Truy cập thẳng tới bộ quản lý thư viện
var Lib = lib_3rd.NewLib(newServer, lib_3rd.WithDefaultConfigFunc[config, Server](DefaultConfig))Copy and modify from "github.com/gofiber/fiber/v3/middleware/timeout"; The handler h must return error; DO NOT USER CTX WRITE
Usage:
var h = func(ctx *fiber.Ctx) error {
// Heavy logic with err from timeoutContext
// DO NOT USE: fhttp.Write... or ctx.Send...
return err
}
app := fhttp.GetFountainInstance()
app.Get("/longtime", middleware.TimeoutMiddleware(h, 2*time.Second))var TimeoutMiddleware = middleware.TimeoutMiddleware(WriteError)var WithConfigKey = Lib.WithConfigKeyfunc AddFiberConfigs
func AddFiberConfigs(fiberConfigs ...fiber.Config) lib_3rd.Option[config]func AddTrustedCloudflareIPs
func AddTrustedCloudflareIPs(ips ...string) lib_3rd.Option[config]func BodyToContext
func BodyToContext(c fiber.Ctx) errorParse all data from body and set all into context
func CreateCookie
func CreateCookie(ctx fiber.Ctx, domain, name, value string, expires time.Time, opts ...CookieOption)CreateCookie set cookie với security defaults — HTTPOnly=true, Secure=prod, SameSite=Lax, Path="/". Phù hợp cho auth-token / session cookie. Dùng CookieOption để override default khi cần.
# Auth cookie cơ bản:
fhttp.CreateCookie(c, "", "__ac_tk", token, time.Now().Add(24*time.Hour))
# Cookie cho JS (vd locale):
fhttp.CreateCookie(c, "", "lang", "vi", time.Now().Add(365*24*time.Hour),
fhttp.WithCookieHTTPOnly(false),
)func DataToContext
func DataToContext(reqParams ...ReqParam) func(c fiber.Ctx) errorSet data{Name, DefaultValue} to context
func DeleteCookie
func DeleteCookie(ctx fiber.Ctx, domain, name string, opts ...CookieOption)DeleteCookie xoá cookie bằng cách set Expires về quá khứ + MaxAge âm. Browser drop ngay. Cookie attributes khác (Path/Domain/Secure/SameSite) PHẢI khớp với cookie ban đầu — nếu không browser sẽ giữ cookie cũ. Truyền cùng các CookieOption mà CreateCookie đã dùng.
func FormRequest
func FormRequest(endpoint string, request any, encoder Encoder, authFn any) (*http.Request, error)func GRPCProxy
func GRPCProxy(h any) fiber.HandlerGRPCProxy experimental
func GetQueryOffsetLimit
func GetQueryOffsetLimit(ctx fiber.Ctx, defaultLimit ...int) (offset, limit int)Cố gắng tìm kiếm các cặp query {offset, limit} hoặc {page, page_size} để tạo offset và limit Ưu tiên sử dụng {page, page_size} trước tiên
func HTTPWriteError
func HTTPWriteError(w http.ResponseWriter, err *froto.RpcError) error*
- Returns an error response
func HTTPWriteErrorWithExtend
func HTTPWriteErrorWithExtend(w http.ResponseWriter, err *froto.RpcError, extend map[froto.Constructor]froto.ObjectInf) error*
- Returns a success response
func HTTPWriteSuccess
func HTTPWriteSuccess(w http.ResponseWriter, v any) error*
- Returns a success response
func HTTPWriteSuccessEmptyContent
func HTTPWriteSuccessEmptyContent(w http.ResponseWriter) error*
- Returns a success response without content
func HTTPWriteSuccessWithExtend
func HTTPWriteSuccessWithExtend(w http.ResponseWriter, data any, extend map[froto.Constructor]froto.ObjectInf) error*
- Returns a success response
func HasAuxiliaryServer
func HasAuxiliaryServer() boolfunc HeaderToMetadataIncoming
func HeaderToMetadataIncoming(c fiber.Ctx) errorMiddleware này sẽ được protoc-gen-fhttp tự động thêm vào các route được tạo ra từ file proto
func HttpRequest
func HttpRequest[T any](client *http.Client, req *http.Request, response T) errorfunc NewFErrorResponse
func NewFErrorResponse(err *froto.RpcError) (string, *froto.RpcError)func ParamToBody
func ParamToBody(reqParams ...ReqParam) func(c fiber.Ctx) errorParse data from param and set all into body
func ParamToContext
func ParamToContext(reqParams ...ReqParam) func(c fiber.Ctx) errorParse data from param and set all into context
func QueryToBody
func QueryToBody(reqParams ...ReqParam) func(c fiber.Ctx) errorParse data from param and set all into body
func QueryToContext
func QueryToContext(reqParams ...ReqParam) func(c fiber.Ctx) errorParse data from query and set all into context
func StructToQueryString
func StructToQueryString(v any) stringfunc TrustedInternalIPs
func TrustedInternalIPs() []stringfunc Validate
func Validate(m any) *froto.RpcError*
- Validates model before do something
func WithAccessInterceptorReqResFilter
func WithAccessInterceptorReqResFilter(filter string) lib_3rd.Option[config]func WithAddress
func WithAddress(addr string) lib_3rd.Option[config]func WithBlockFallback
func WithBlockFallback(blockFallback func(fiber.Ctx) error) lib_3rd.Option[config]func WithCORSAllowCredentials
func WithCORSAllowCredentials(allow ...bool) lib_3rd.Option[config]func WithCORSAllowOrigins
func WithCORSAllowOrigins(origins ...string) lib_3rd.Option[config]func WithCacheExpiration
func WithCacheExpiration(d time.Duration) lib_3rd.Option[config]func WithCacheStorageName
func WithCacheStorageName(name string) lib_3rd.Option[config]func WithContextTimeout
func WithContextTimeout(timeout time.Duration) lib_3rd.Option[config]func WithDisableAccessInterceptor
func WithDisableAccessInterceptor(disable ...bool) lib_3rd.Option[config]func WithDisableMetricInterceptor
func WithDisableMetricInterceptor(disable ...bool) lib_3rd.Option[config]func WithDisableTraceInterceptor
func WithDisableTraceInterceptor(disable ...bool) lib_3rd.Option[config]func WithEmbedFs
func WithEmbedFs(fs embed.FS) lib_3rd.Option[config]func WithEmbedPath
func WithEmbedPath(path string) lib_3rd.Option[config]func WithEnableAccessInterceptorReq
func WithEnableAccessInterceptorReq(enable ...bool) lib_3rd.Option[config]func WithEnableAccessInterceptorRes
func WithEnableAccessInterceptorRes(enable ...bool) lib_3rd.Option[config]func WithEnableCORS
func WithEnableCORS(enable ...bool) lib_3rd.Option[config]func WithEnableCache
func WithEnableCache(enable ...bool) lib_3rd.Option[config]func WithEnableLimiter
func WithEnableLimiter(enable ...bool) lib_3rd.Option[config]func WithEnableLocalMainIP
func WithEnableLocalMainIP(enable ...bool) lib_3rd.Option[config]func WithEnableMinify
func WithEnableMinify(enable ...bool) lib_3rd.Option[config]func WithEnableOPA
func WithEnableOPA(enable ...bool) lib_3rd.Option[config]func WithEnableResponseTime
func WithEnableResponseTime(enable ...bool) lib_3rd.Option[config]func WithEnableSentinel
func WithEnableSentinel(enable ...bool) lib_3rd.Option[config]func WithEnableSouin
func WithEnableSouin(enable ...bool) lib_3rd.Option[config]func WithEnableTLS
func WithEnableTLS(enable ...bool) lib_3rd.Option[config]func WithEnableTrustedCustomHeader
func WithEnableTrustedCustomHeader(enable ...bool) lib_3rd.Option[config]func WithEnableWAF
func WithEnableWAF(enable ...bool) lib_3rd.Option[config]func WithEnableWebsocketCheckOrigin
func WithEnableWebsocketCheckOrigin(enable ...bool) lib_3rd.Option[config]func WithEnableWebsocketCompression
func WithEnableWebsocketCompression(enable ...bool) lib_3rd.Option[config]func WithFiberConfigs
func WithFiberConfigs(fiberConfigs ...fiber.Config) lib_3rd.Option[config]func WithIdempotencyKeyHeader
func WithIdempotencyKeyHeader(header string) lib_3rd.Option[config]func WithIdempotencyKeySecret
func WithIdempotencyKeySecret(secret string) lib_3rd.Option[config]func WithIdempotencyLifetime
func WithIdempotencyLifetime(d time.Duration) lib_3rd.Option[config]func WithIdempotencyStorageName
func WithIdempotencyStorageName(name string) lib_3rd.Option[config]func WithLimiterExpiration
func WithLimiterExpiration(d time.Duration) lib_3rd.Option[config]func WithLimiterMax
func WithLimiterMax(max int) lib_3rd.Option[config]func WithLimiterStorageName
func WithLimiterStorageName(name string) lib_3rd.Option[config]func WithMetricCounter
func WithMetricCounter(counter metrics.Counter) lib_3rd.Option[config]func WithMetricHistogram
func WithMetricHistogram(histogram metrics.Histogram) lib_3rd.Option[config]func WithMetricProviderName
func WithMetricProviderName(name string) lib_3rd.Option[config]func WithMinifyMinifyJSON
func WithMinifyMinifyJSON(enable ...bool) lib_3rd.Option[config]func WithMinifyMinifySVG
func WithMinifyMinifySVG(enable ...bool) lib_3rd.Option[config]func WithMinifyMinifyXML
func WithMinifyMinifyXML(enable ...bool) lib_3rd.Option[config]func WithName
func WithName(name string) lib_3rd.Option[config]func WithNetworkProtocol
func WithNetworkProtocol(protocol string) lib_3rd.Option[config]func WithOPAPolicy
func WithOPAPolicy(policy string) lib_3rd.Option[config]func WithOPAQuery
func WithOPAQuery(query string) lib_3rd.Option[config]func WithOPAURL
func WithOPAURL(url string) lib_3rd.Option[config]func WithResourceExtract
func WithResourceExtract(resourceExtract func(fiber.Ctx) string) lib_3rd.Option[config]func WithServerHTTPTimeout
func WithServerHTTPTimeout(timeout time.Duration) lib_3rd.Option[config]func WithServerReadHeaderTimeout
func WithServerReadHeaderTimeout(timeout time.Duration) lib_3rd.Option[config]func WithServerReadTimeout
func WithServerReadTimeout(timeout time.Duration) lib_3rd.Option[config]func WithServerWriteTimeout
func WithServerWriteTimeout(timeout time.Duration) lib_3rd.Option[config]func WithSlowLogThreshold
func WithSlowLogThreshold(duration time.Duration) lib_3rd.Option[config]func WithSouinExcludedRegex
func WithSouinExcludedRegex(regex string) lib_3rd.Option[config]func WithSouinHandler
func WithSouinHandler(h middleware.SouinHandler) lib_3rd.Option[config]WithSouinHandler injects a pre-built SouinHandler into the config. This avoids importing Souin's heavy transitive dependency chain (Caddy, etc.) from the fhttp package.
Usage:
// In application code (imports souin/pkg/middleware directly):
cfg := middleware.BuildSouinConfiguration(
middleware.SouinWithTTL(30*time.Second),
)
handler := souinmw.NewHTTPCacheHandler(cfg)
fhttp.WithSouinHandler(myAdapter{handler})func WithSouinLogLevel
func WithSouinLogLevel(level string) lib_3rd.Option[config]func WithSouinTTL
func WithSouinTTL(d time.Duration) lib_3rd.Option[config]func WithTLSCertFile
func WithTLSCertFile(path string) lib_3rd.Option[config]func WithTLSClientAuth
func WithTLSClientAuth(auth string) lib_3rd.Option[config]func WithTLSClientCAs
func WithTLSClientCAs(ca []string) lib_3rd.Option[config]func WithTLSKeyFile
func WithTLSKeyFile(path string) lib_3rd.Option[config]func WithTLSSessionCache
func WithTLSSessionCache(s tls.ClientSessionCache) lib_3rd.Option[config]func WithTrustedPlatform
func WithTrustedPlatform(platform string) lib_3rd.Option[config]func WithWAFBlock
func WithWAFBlock(block ...bool) lib_3rd.Option[config]func WithWAFDirectives
func WithWAFDirectives(directives string) lib_3rd.Option[config]func WithWebsocketHandshakeTimeout
func WithWebsocketHandshakeTimeout(timeout time.Duration) lib_3rd.Option[config]func WithWebsocketReadBufferSize
func WithWebsocketReadBufferSize(size int) lib_3rd.Option[config]func WithWebsocketWriteBufferSize
func WithWebsocketWriteBufferSize(size int) lib_3rd.Option[config]func WriteError
func WriteError(c fiber.Ctx, err *froto.RpcError) error*
- Returns an error response
func WriteErrorWithExtend
func WriteErrorWithExtend(c fiber.Ctx, err *froto.RpcError, extend any) error*
- Returns a success response
func WriteErrorWithGRPCExtend
func WriteErrorWithGRPCExtend(c fiber.Ctx, err *froto.RpcError, extend map[froto.Constructor]froto.ObjectInf) error*
- Returns a success response
func WriteNotImplementedError
func WriteNotImplementedError(c fiber.Ctx) error*
- Returns an error response
func WriteSuccess
func WriteSuccess(c fiber.Ctx, v any) error*
- Returns a success response
func WriteSuccessEmptyContent
func WriteSuccessEmptyContent(c fiber.Ctx) error*
- Returns a success response without content
func WriteSuccessWithExtend
func WriteSuccessWithExtend(c fiber.Ctx, data any, extend any) error*
- Returns a success response
func WriteSuccessWithGRPCExtend
func WriteSuccessWithGRPCExtend(c fiber.Ctx, data any, extend map[froto.Constructor]froto.ObjectInf) error*
- Returns a success response
func WriteSuccessWithPaging
func WriteSuccessWithPaging(c fiber.Ctx, v any, paging *Paging) error*
- Returns a success response
func WriteSuccessWithStatus
func WriteSuccessWithStatus(c fiber.Ctx, code int, v any) error*
- Returns a success response
func WriteWithErrorProcess
func WriteWithErrorProcess(c fiber.Ctx, err error) errortype CookieOption
CookieOption tinh chỉnh cookie attribute. Dùng cho CreateCookie / DeleteCookie khi cần override default (vd cookie không HTTPOnly cho JS-side feature flag, hoặc SameSite=None cho cross-site iframe).
type CookieOption func(*fiber.Cookie)func WithCookieHTTPOnly
func WithCookieHTTPOnly(httpOnly bool) CookieOptionWithCookieHTTPOnly bật/tắt HTTPOnly. Default true (an toàn nhất, JS không đọc được — chống XSS đánh cắp). Tắt khi cookie cần JS đọc (analytics, ...).
func WithCookieMaxAge
func WithCookieMaxAge(seconds int) CookieOptionWithCookieMaxAge set MaxAge (seconds). 0 = session cookie. <0 = delete ngay. Browser ưu tiên MaxAge hơn Expires khi cả hai cùng set.
func WithCookiePath
func WithCookiePath(path string) CookieOptionWithCookiePath set Path attribute (default "/").
func WithCookieSameSite
func WithCookieSameSite(mode string) CookieOptionWithCookieSameSite set SameSite mode. Default "Lax". Dùng "Strict" cho extra CSRF protection (chặn cross-origin link clicks), "None" cho 3rd-party embed (yêu cầu Secure=true).
func WithCookieSecure
func WithCookieSecure(secure bool) CookieOptionWithCookieSecure bật/tắt Secure (HTTPS-only). Default = env.IsProdEnvironment(). Override để force-on trong dev (https://localhost) hoặc force-off cho test.
type Decoder
type Decoder interface {
Decode(dst any, src map[string][]string) error
}type Encoder
type Encoder interface {
Encode(src any, dst map[string][]string) error
}type FormAuthorization
type FormAuthorization func(url.Values)type Paging
type Paging struct {
CurrentOffset int `json:"current_offset,omitempty"` // for load more
NextOffset int `json:"next_offset,omitempty"` // for load more
Limit int `json:"limit,omitempty"` // for load more
Total int `json:"total,omitempty"` // total items
CurrentPage int `json:"current_page,omitempty"` // for page
PageSize int `json:"page_size,omitempty"` // for page
NextPage int `json:"next_page,omitempty"` // for page
PrevPage int `json:"prev_page,omitempty"` // for page
TotalPages int `json:"total_pages,omitempty"` // for page
}type ProbesFn
type ProbesFn func(context.Context) errortype ReqParam
Models
type ReqParam struct {
Param string
Name string // Name of param when it convert to body
DefaultValue string
}type RequestAuthorization
type RequestAuthorization func(*http.Request)func AuthorizeBasic
func AuthorizeBasic(user, password string) RequestAuthorizationtype Response
*
- Defines a response object
type Response[T any] struct {
Message string `json:"message,omitempty"`
Data T `json:"data,omitempty"`
DataExtend any `json:"data_extend,omitempty"` // map[froto.Constructor]froto.ObjectInf or encrypted data as base64 string
Paging *Paging `json:"paging,omitempty"`
Description string `json:"description,omitempty"`
Status int `json:"status,omitempty"`
}func NewResponse
func NewResponse[T any]() *Response[T]func (*Response[T]) Parse
func (res *Response[T]) Parse(body []byte) errortype Server
FountainAPI type;
type Server struct {
*runnable.ServerInstance
*fiber.App
Store *session.Store
// contains filtered or unexported fields
}func GetAuxiliaryServer
func GetAuxiliaryServer() *ServerPanic if auxiliary server is not available
func (*Server) CreateGovernanceServer
func (s *Server) CreateGovernanceServer()CreateGovernanceServer func;
func (*Server) CreateMetricsServer
func (s *Server) CreateMetricsServer()CreateMetricsServer func;
CHANGELOG (fiber v3 migration): the Fiber v2 monitor middleware is no longer available in v3 and there is no in-tree replacement, so the previous /monitor route has been removed. The Prometheus /metrics route remains and is the supported observability surface going forward.
func (*Server) Destroy
func (s *Server) Destroy() (err error)Stop func;
func (*Server) GetConfig
func (s *Server) GetConfig() *configfunc (*Server) GetName
func (s *Server) GetName() stringName configuration name
func (*Server) GetPackageName
func (s *Server) GetPackageName() stringPackageName package name
func (*Server) GracefulStop
func (s *Server) GracefulStop(ctx context.Context) errorfunc (*Server) InitHealthCheckPath
func (s *Server) InitHealthCheckPath(path string)func (*Server) InitHealthCheckRoute
func (s *Server) InitHealthCheckRoute(router fiber.Router)func (*Server) RegisterReadyProbes
func (s *Server) RegisterReadyProbes(name string, probesFn ProbesFn) *Serverfunc (*Server) Serve
func (s *Server) Serve() (err error)Serve func; Need run in a goroutine
func (*Server) Serving
func (s *Server) Serving()Serving func; Need run in a goroutine
func (*Server) SetAccessInterceptorResCelProgram
func (s *Server) SetAccessInterceptorResCelProgram() *ServerGenerated by gomarkdoc