Go Integration Guide

The ztlayer-go SDK is a heavily optimized, concurrent-safe client for protecting Go microservices. It provides a native net/http middleware handler that intercepts requests and queries the ZTLayer Edge via persistent HTTP keep-alives.


1. Installation

Install the Go module:

go get github.com/ztlayer/ztlayer-go

2. Configuration & Initialization

Create the ZTLayer client instance once during your application's main() initialization. It automatically manages a high-performance HTTP connection pool.

package main
 
import (
	"log"
	"net/http"
	"os"
 
	"github.com/ztlayer/ztlayer-go"
)
 
func main() {
	// 1. Initialize ZTLayer Client
	ztClient, err := ztlayer.NewClient(ztlayer.Config{
		APIKey:   os.Getenv("ZTLAYER_API_KEY"),
		FailMode: ztlayer.FailOpen, // Recommended
	})
	if err != nil {
		log.Fatalf("Failed to initialize ZTLayer: %v", err)
	}
 
	// 2. Define your application routes
	mux := http.NewServeMux()
	mux.HandleFunc("/api/data", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`{"status": "secure"}`))
	})
 
	// 3. Wrap your mux with the ZTLayer Middleware
	log.Println("Server listening on :8080")
	http.ListenAndServe(":8080", ztClient.Middleware(mux))
}

3. Gin Framework Integration

If you are using the popular Gin framework, the SDK provides a dedicated Gin handler.

package main
 
import (
	"os"
 
	"github.com/gin-gonic/gin"
	"github.com/ztlayer/ztlayer-go"
	ztgin "github.com/ztlayer/ztlayer-go/gin"
)
 
func main() {
	r := gin.Default()
 
	ztClient, _ := ztlayer.NewClient(ztlayer.Config{
		APIKey: os.Getenv("ZTLAYER_API_KEY"),
	})
 
	// Apply ZTLayer globally
	r.Use(ztgin.Middleware(ztClient))
 
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "pong"})
	})
 
	r.Run() // listen and serve on 0.0.0.0:8080
}

4. Trusting Proxies

If your Go application runs behind an AWS ALB or Nginx proxy, you must instruct the ZTLayer client to extract the IP from the X-Forwarded-For header.

ztClient, _ := ztlayer.NewClient(ztlayer.Config{
    APIKey:      os.Getenv("ZTLAYER_API_KEY"),
    TrustProxies: true, // Uses X-Forwarded-For automatically
})