在Go语言中进行类型转换时进行错误检查。

huangapple go评论70阅读模式
英文:

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(&quot;user&quot;)
token := user.(*jwt.Token)

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

fmt.Println(&quot;Username: &quot;, claims[&quot;name&quot;], &quot;User ID: &quot;, claims[&quot;jti&quot;])

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.
}

huangapple
  • 本文由 发表于 2017年9月8日 08:27:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/46106894.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定