gin

package
v0.2.7 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 11 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bind added in v0.2.7

func Bind(c *gin.Context, obj any) bool

Bind reads the JSON body into obj (a struct pointer) and checks its "binding" and "validate" tags. On failure it writes a VALIDATION response through Respond and returns false, so a handler only needs:

if !libgin.Bind(c, &req) {
	return
}

The body is cached, so a later c.ShouldBindBodyWith can read it again.

Example

ExampleBind shows how a handler reads and checks a JSON body in one call. On failure Bind has already written a VALIDATION response.

package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"

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

// publishReq is a request body: "binding" tags are checked by gin, "validate"
// tags by the validator package.
type publishReq struct {
	Id    int64  `json:"id" binding:"required"`
	Title string `json:"title" validate:"max=10"`
}

func main() {
	slog.SetDefault(slog.New(slog.NewTextHandler(io.Discard, nil)))

	router := gin.New()
	router.POST("/publish", func(c *gin.Context) {
		var req publishReq
		if !libgin.Bind(c, &req) {
			return
		}
		c.JSON(http.StatusOK, gin.H{"id": req.Id})
	})

	for _, body := range []string{
		`{"id":7,"title":"hello"}`,          // valid
		`{"title":"hello"}`,                 // binding tag: id is required
		`{"id":7,"title":"a long title!!"}`, // validate tag: title too long
	} {
		w := httptest.NewRecorder()
		req := httptest.NewRequest(http.MethodPost, "/publish", strings.NewReader(body))
		req.Header.Set("Content-Type", "application/json")
		router.ServeHTTP(w, req)

		var resp map[string]any
		_ = json.Unmarshal(w.Body.Bytes(), &resp)
		fmt.Println(w.Code, resp["errorCode"])
	}
}
Output:
200 <nil>
400 VALIDATION
400 VALIDATION

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

func Respond added in v0.2.7

func Respond(c *gin.Context, err error)

Respond writes err as a safe JSON error response and logs the full detail. Every error response of the adapter goes through Respond: errors returned by the service layer (passed unchanged) and the adapter's own errors such as bind or validation failures (built with safeerror.Validation). It is the one place these errors are logged, so dao and service code must not log the errors they return.

The client sees only the status, the safe message and errorCode; the log line also has the internal cause, the request id (the same as the X-Request-Id response header set by the slog-gin middleware) and the user id when the request is authenticated. Log levels follow safeerror.Report.

Example

ExampleRespond shows the one exit for error responses in a handler. The client gets only the status, the safe message and errorCode; the log record also keeps the internal cause.

package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"

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

func main() {
	var buf bytes.Buffer
	slog.SetDefault(slog.New(slog.NewJSONHandler(&buf, nil)))

	router := gin.New()
	router.GET("/articles/:id", func(c *gin.Context) {
		// stands for a service call that failed on the database
		err := safeerror.Database(errors.New(`pq: relation "article" does not exist`))
		libgin.Respond(c, err)
	})
	router.DELETE("/articles/:id", func(c *gin.Context) {
		// stands for a business rule checked by the service
		libgin.Respond(c, safeerror.Conflict("article status does not equal PUBLISHED", nil))
	})

	for _, method := range []string{http.MethodGet, http.MethodDelete} {
		buf.Reset()
		w := httptest.NewRecorder()
		router.ServeHTTP(w, httptest.NewRequest(method, "/articles/7", nil))
		fmt.Println(w.Code, w.Body.String())

		var rec map[string]any
		_ = json.Unmarshal(buf.Bytes(), &rec)
		fmt.Println(rec["level"], rec["code"], rec["detail"])
	}
}
Output:
500 {"code":500,"message":"database error, please retry later","errorCode":"DATABASE"}
ERROR DATABASE code=DATABASE msg="database error, please retry later" internal=pq: relation "article" does not exist
409 {"code":409,"message":"article status does not equal PUBLISHED","errorCode":"CONFLICT"}
WARN CONFLICT code=CONFLICT msg="article status does not equal PUBLISHED" internal=<nil>

func Validate added in v0.2.7

func Validate(c *gin.Context, obj any) bool

Validate checks the "validate" tags of obj, e.g. query parameters the handler filled in itself. On failure it writes a VALIDATION response through Respond and returns false.

Example

ExampleValidate shows how to check values that do not come from a JSON body, e.g. query parameters.

package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strconv"

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

// listParams holds query parameters the handler fills in itself.
type listParams struct {
	Page int    `validate:"min=1"`
	Sort string `validate:"omitempty,oneof=title createdAt"`
}

func main() {
	slog.SetDefault(slog.New(slog.NewTextHandler(io.Discard, nil)))

	router := gin.New()
	router.GET("/articles", func(c *gin.Context) {
		var p listParams
		p.Page, _ = strconv.Atoi(c.DefaultQuery("page", "1"))
		p.Sort = c.Query("sort")
		if !libgin.Validate(c, &p) {
			return
		}
		c.JSON(http.StatusOK, gin.H{"page": p.Page})
	})

	for _, query := range []string{"?page=2&sort=title", "?page=0", "?sort=views"} {
		w := httptest.NewRecorder()
		router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/articles"+query, nil))

		var resp map[string]any
		_ = json.Unmarshal(w.Body.Bytes(), &resp)
		fmt.Println(w.Code, resp["errorCode"])
	}
}
Output:
200 <nil>
400 VALIDATION
400 VALIDATION

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 download serves files under one directory as downloads on a Gin engine.
Package download serves files under one directory as downloads on a Gin engine.
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