How to use gin.Context.MustGet()
in server:= socketio.NewServer(nil)
I used authorized to check the token and before into socketio handler.
authorized.GET("/socket.io", gin.WrapH(server))
authorized.POST("/socket.io", gin.WrapH(server))
I set some information for the client in authorized .
func AuthRequired(c *gin.Context) {
...
c.Set("username", claims.Username) // parse from the token
...
}
I know I can do this to get the username from gin.Context
authorized.GET("/content", func(c *gin.Context) {
fmt.Println(c.MustGet("username"))
...
})
Is there any way to get the username from the server? Or how to pass the variable into here?
server.OnEvent("/", "chat", func(s socketio.Conn, msg string) string {
fmt.Println("chat: ", msg)
s.Emit("response", msg)
return "recv " + msg
})
Although there is s.RemoteHeader()
that I can get the token and parse it, it is repeated to parse it again.
you should add username from AuthRequired like below:
c.Request.Header.Set("username", claims.Username)
and then use it in server.OnEvent function like below:
s.RemoteHeader().Get("username")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.