package main
import (
	"fmt"
	"time"
	"github.com/dgrijalva/jwt-go"
)
const (
	SECRETKEY = "202203021124355xxx" //私钥
)
// 自定义 Claims
type CustomClaims struct {
	UserId int64
	jwt.StandardClaims
}
func main() {
	//生成 token
	maxAge := 60 * 60 * 24
	customClaims := &CustomClaims{
		UserId: 11, //用户 id
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(time.Duration(maxAge) * time.Second).Unix(), // 过期时间,必须设置
			Issuer:    "root",                                                     // 非必须,也可以填充用户名,
		},
	}
	//采用 HMAC SHA256 加密算法
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, customClaims)
	tokenString, err := token.SignedString([]byte(SECRETKEY))
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("token: %v\n", tokenString)
	fmt.Println("Token=====", tokenString)
	//解析 token
	ret, err := ParseToken(tokenString)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("userinfo: %v\n", ret)
	fmt.Println("====创建时间", ret.ExpiresAt)
}
// 解析 token
func ParseToken(tokenString string) (*CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(SECRETKEY), nil
	})
	if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
		return claims, nil
	} else {
		return nil, err
	}
}