gin

package
v0.1.38 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func InitGin

func InitGin(corsOrigins []string, filters ...slogGin.Filter) *gin.Engine

InitGin creates and configures a new Gin engine. It always runs in ReleaseMode to suppress framework debug output in all environments. It attaches structured slog-based request logging and a recovery middleware, and optionally configures CORS when corsOrigins is non-empty. Entries containing * are treated as wildcard patterns and matched via AllowOriginFunc (single-level wildcard * means one label, no dots). The caller is responsible for passing the correct origin list. Pass nil or an empty slice to disable CORS.

filters is optional (trailing variadic, so existing callers passing only corsOrigins are unaffected) and is passed straight through to slogGin's own request-logging middleware - see github.com/samber/slog-gin's Filter type and its filters.go helpers (IgnorePath/IgnorePathPrefix/IgnoreStatus/etc.). A filter returning false for a given request skips logging it entirely - e.g. slogGin.IgnorePath("/") to silence a noisy health-check endpoint.

Example

ExampleInitGin shows how to create a Gin engine with no CORS. Pass nil or an empty slice when all cross-origin requests should be blocked.

package main

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	libgin "github.com/phcp-tech/common-library-golang/gin"
)

func main() {
	router := libgin.InitGin(nil)
	router.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"status": "ok"})
	})
	fmt.Println(router != nil)
}
Output:
true
Example (Cors)

ExampleInitGin_cors shows how to enable CORS for a list of allowed origins. Exact origins and wildcard patterns (entries containing *) can be mixed. A wildcard * matches exactly one subdomain label (no dots).

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/gin-gonic/gin"
	libgin "github.com/phcp-tech/common-library-golang/gin"
)

func main() {
	router := libgin.InitGin([]string{
		"https://app.example.com", // exact origin
		"https://*.example.com",   // wildcard: root + any single subdomain
	})
	router.GET("/api/data", func(c *gin.Context) {
		c.Status(http.StatusOK)
	})

	// Allowed origin receives its own origin in the response header.
	w := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/api/data", nil)
	req.Header.Set("Origin", "https://app.example.com")
	router.ServeHTTP(w, req)
	fmt.Println(w.Header().Get("Access-Control-Allow-Origin"))

	// Blocked origin receives no CORS header.
	w2 := httptest.NewRecorder()
	req2 := httptest.NewRequest(http.MethodGet, "/api/data", nil)
	req2.Header.Set("Origin", "https://test.com")
	router.ServeHTTP(w2, req2)
	fmt.Println(w2.Header().Get("Access-Control-Allow-Origin"))
}
Output:
https://app.example.com
Example (Filters)

ExampleInitGin_filters shows how to silence request logging for specific endpoints - e.g. a noisy health-check hit repeatedly by a load balancer, or a metrics-scrape path. filters is a trailing variadic (InitGin(corsOrigins []string, filters ...slogGin.Filter)), so filtering several endpoints needs no new plumbing - either pass multiple slogGin.Filter values, or a single IgnorePath(...) call listing several paths (IgnorePath itself is variadic too); the two styles below are equivalent. A request is logged unless ANY filter returns false for it - filters combine with OR, not AND.

package main

import (
	"bytes"
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/gin-gonic/gin"
	libgin "github.com/phcp-tech/common-library-golang/gin"

	slogGin "github.com/samber/slog-gin"
)

func main() {
	// Route logging to a buffer instead of stderr so this example can
	// assert on it. Real callers never do this - see log.InitLog(), which
	// InitGin's own doc comment mentions is what redirects slog.Default().
	var buf bytes.Buffer
	slog.SetDefault(slog.New(slog.NewTextHandler(&buf, nil)))

	router := libgin.InitGin(nil,
		slogGin.IgnorePath("/healthz", "/readyz"), // one call, multiple paths
		slogGin.IgnorePathPrefix("/metrics"),      // a second, distinct filter
	)
	for _, path := range []string{"/healthz", "/readyz", "/metrics/cpu", "/api/data"} {
		router.GET(path, func(c *gin.Context) { c.Status(http.StatusOK) })
	}

	for _, path := range []string{"/healthz", "/readyz", "/metrics/cpu", "/api/data"} {
		router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, path, nil))
	}

	fmt.Println(strings.Contains(buf.String(), "/healthz"))
	fmt.Println(strings.Contains(buf.String(), "/readyz"))
	fmt.Println(strings.Contains(buf.String(), "/metrics/cpu"))
	fmt.Println(strings.Contains(buf.String(), "/api/data"))
}
Output:
false
false
false
true

Types

This section is empty.

Directories

Path Synopsis
Package component provides Gin lifecycle integration for bootstrap.
Package component provides Gin lifecycle integration for bootstrap.
Package pprof exposes Go runtime profiling endpoints on a Gin engine via github.com/gin-contrib/pprof.
Package pprof exposes Go runtime profiling endpoints on a Gin engine via github.com/gin-contrib/pprof.

Jump to

Keyboard shortcuts

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