Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error checking while type casting in Go

Tags:

go

jwt

I am currently adding JWT authentication to my Go web app and I have some concerns when it comes to type casting in go and the automatic Panic if it fails. My code looks like this:
(c being the context package)

user := c.Get("user")
token := user.(*jwt.Token)

claims := token.Claims.(jwt.MapClaims)

fmt.Println("Username: ", claims["name"], "User ID: ", claims["jti"])

As you can see I use type casting on multiple lines, yet if this operation failed it will panic and ultimately cause the server to crash. Is there any possible way to check for an error in this case?
I am quite new to web development in Go so my apologies, all help is appreciated!

like image 725
Ethan Avatar asked Jul 11 '26 04:07

Ethan


1 Answers

Type assertions (somevar.(sometype)) return a (sometype, bool), so you can check the bool. Idiomatically that's:

token, ok := user.(*jwt.Token)
if !ok {
    // handle the fail case. `token` is nil here.
}
like image 155
Adam Smith Avatar answered Jul 16 '26 12:07

Adam Smith