


Installation
import (
"github.com/cego/go-lib/v2/logger"
"github.com/cego/go-lib/v2/renderer"
"github.com/cego/go-lib/v2/forwardauth"
"github.com/cego/go-lib/v2/headers"
"github.com/cego/go-lib/v2/serve"
"github.com/cego/go-lib/v2/periodic"
)
Using Logger
l := logger.New()
l.Debug("Very nice")
err := errors.New("An error")
l.Error("An error occurred in readme", logger.GetSlogAttrFromError(err))
handleFunc := func(writer http.ResponseWriter, request *http.Request) {
l.Debug("Very nice", logger.GetSlogAttrFromRequest(request))
}
// With custom log level
l := logger.NewWithLevel(slog.LevelInfo)
// Set as global slog default
slog.SetDefault(l)
// Testing with mock logger
l := logger.NewMock()
r := renderer.New(l)
Using Renderer with builtin logging
l := logger.New()
r := renderer.New(l)
handleFunc := func(writer http.ResponseWriter, request *http.Request) {
r.Text(w, http.StatusOK, "Action package excitement !!!")
}
Using ForwardAuthHandler
Use builtin http client (timeout 10s)
mux := http.NewServeMux()
fa := forwardauth.New(l, "https://sso.example.com/auth", "myservice.example.com")
mux.Handle("/data", fa.Handler(reverseProxy))
mux.Handle("/data", fa.HandlerFunc(func (w http.ResponseWriter, req *http.Request) {
_,_ = w.Write()
}))
Bring your own http client
mux := http.NewServeMux()
httpClient := &http.Client{Timeout: time.Duration(1) * time.Second}
fa := forwardauth.New(l, "https://sso.example.com/auth", "myservice.example.com", forwardauth.WithHTTPClient(httpClient))
mux.Handle("/data", fa.Handler(reverseProxy))
mux.Handle("/data", fa.HandlerFunc(func (w http.ResponseWriter, req *http.Request) {
_,_ = w.Write()
}))
req.Header.Get(headers.Authorization)
req.Header.Get(headers.XForwardedFor)
Available constants: XForwardedProto, XForwardedMethod, XForwardedHost, XForwardedUri, XForwardedFor, Accept, UserAgent, Cookie, Authorization, RemoteUser, ContentType
Using Periodic
Context-aware periodic task execution with jitter support.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
periodic.Run(ctx, 2*time.Second, time.Duration(rand.Intn(1000))*time.Millisecond, func() {
fmt.Println("runs every 2 seconds until ctx is cancelled")
})
Using Serve (Graceful Shutdown)
Graceful HTTP server shutdown with a configurable delay for load balancer deregistration.
srv := serve.WithDefaults(&http.Server{Addr: ":8080", Handler: myHandler})
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
err := serve.ListenAndServe(ctx, srv, slog.Default())