英文:
Error checking while type casting in Go
问题
我目前正在为我的Go Web应用程序添加JWT身份验证,并且在Go中进行类型转换和自动恐慌失败时有一些顾虑。我的代码如下:(c是上下文包)
user := c.Get("user")
token := user.(*jwt.Token)
claims := token.Claims.(jwt.MapClaims)
fmt.Println("Username: ", claims["name"], "User ID: ", claims["jti"])
正如你所看到的,我在多行上使用了类型转换,但是如果此操作失败,它将引发恐慌并最终导致服务器崩溃。在这种情况下,有没有可能检查错误?我对Go的Web开发还很新,所以请原谅,非常感谢你的帮助!
英文:
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: <br>(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? <br> I am quite new to web development in Go so my apologies, all help is appreciated!
答案1
得分: 23
类型断言(somevar.(sometype)
)返回一个(sometype, bool)
,因此你可以检查bool值。按照惯例,可以这样写:
token, ok := user.(*jwt.Token)
if !ok {
// 处理失败的情况。这里`token`为nil。
}
英文:
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.
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论