gin

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 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) *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.

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

Types

This section is empty.

Directories

Path Synopsis
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