I am trying to create some auth functions in Go. I will receive multiple auth types, and different auth types share some utils functions and need to behave slightly differently in those utils functions. I want to use sub-functions to achieve these differences to reduce duplicates.
For example, all auth types share validate_token
function, however inside validate_token
function, I need a parse_token
function which behaves differently according to the auth type.
The below codes are how I am trying to approach this, but I get error: panic: runtime error: invalid memory address or nil pointer dereference
in testing. When I change func (m authType1) parse_token
to func (m auth) parse_token
and call the parse_token
function by m.parse_token
, the error goes away (But I do need parse_token
to be different according to different auth types).
Does anyone know how I should fix these codes? Thanks a lot!
type auth struct {
config AuthConfig
}
type authType1 struct {
auth
}
type authType2 struct {
auth
}
type parseToken interface {
parse_token(token *oauth2.Token) (*jwt.Token, error)
}
func (m auth) validateToken(token *oauth2.Token, f parseToken) (*jwt.Token, error) {
...
jwtToken, err := f.parse_token(token)
return jwtToken, err
}
func (m authType1) parse_token(token *oauth2.Token) (*jwt.Token, error) {
...
}
func (m authType2) parse_token(token *oauth2.Token) (*jwt.Token, error) {
...
}
Luna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.