Getting Started
Install go-jwt, connect Redis, and issue your first token pair with the core package (goJwt).
Prerequisites
- Go 1.24 or higher
- Redis server
Installation
Using go get
go get github.com/pardnchiu/go-jwt
Import path after v1.0.3:
import goJwt "github.com/pardnchiu/go-jwt/core"
From Source
git clone https://github.com/pardnchiu/go-jwt.git
cd go-jwt
go build ./...
Minimal example
package main
import (
"log"
"net/http"
goJwt "github.com/pardnchiu/go-jwt/core"
)
func main() {
jwtAuth, err := goJwt.New(goJwt.Config{
Redis: goJwt.Redis{
Host: "localhost",
Port: 6379,
DB: 0,
},
})
if err != nil {
log.Fatalf("init failed: %v", err)
}
defer jwtAuth.Close()
http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
result := jwtAuth.Create(w, r, &goJwt.Auth{
ID: "user-1",
Name: "Alice",
Email: "alice@example.com",
Role: "admin",
})
if !result.Success {
http.Error(w, result.Error, result.StatusCode)
return
}
w.WriteHeader(result.StatusCode)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
New loads or auto-generates ECDSA P-256 keys, pings Redis, and applies Option defaults (15m access, 7d refresh).
Protect a route (net/http)
mux := http.NewServeMux()
mux.Handle("/me", jwtAuth.HTTPMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, ok := goJwt.GetAuthDataFromHTTPRequest(r)
if !ok {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
_ = user
})))
Protect a route (Gin)
r := gin.Default()
auth := r.Group("/")
auth.Use(jwtAuth.GinMiddleware())
auth.GET("/me", func(c *gin.Context) {
user, ok := goJwt.GetAuthDataFromGinContext(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
c.JSON(http.StatusOK, user)
})
Next steps
- Tune Redis, cookies, and refresh thresholds on Configuration
- Review lifecycle and fingerprint design on Core Concepts
- Browse exported symbols on API Reference