github.com/aarzilli/tools@v0.0.0-20151123112009-0d27094f75e0/appengine/login/googlesignin/jwt-go/example_test.go (about) 1 package jwt_test 2 3 import ( 4 "fmt" 5 "github.com/dgrijalva/jwt-go" 6 "time" 7 ) 8 9 func ExampleParse(myToken string, myLookupKey func(interface{}) (interface{}, error)) { 10 token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) { 11 return myLookupKey(token.Header["kid"]) 12 }) 13 14 if err == nil && token.Valid { 15 fmt.Println("Your token is valid. I like your style.") 16 } else { 17 fmt.Println("This token is terrible! I cannot accept this.") 18 } 19 } 20 21 func ExampleNew(mySigningKey []byte) (string, error) { 22 // Create the token 23 token := jwt.New(jwt.SigningMethodHS256) 24 // Set some claims 25 token.Claims["foo"] = "bar" 26 token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix() 27 // Sign and get the complete encoded token as a string 28 tokenString, err := token.SignedString(mySigningKey) 29 return tokenString, err 30 } 31 32 func ExampleParse_errorChecking(myToken string, myLookupKey func(interface{}) (interface{}, error)) { 33 token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) { 34 return myLookupKey(token.Header["kid"]) 35 }) 36 37 if token.Valid { 38 fmt.Println("You look nice today") 39 } else if ve, ok := err.(*jwt.ValidationError); ok { 40 if ve.Errors&jwt.ValidationErrorMalformed != 0 { 41 fmt.Println("That's not even a token") 42 } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 { 43 // Token is either expired or not active yet 44 fmt.Println("Timing is everything") 45 } else { 46 fmt.Println("Couldn't handle this token:", err) 47 } 48 } else { 49 fmt.Println("Couldn't handle this token:", err) 50 } 51 52 }