I have this piece of code in a middleware func:
params := r.URL.Query()
tok := params["x-huru-api-token"][0];
if tok == nil {
tok := r.Header.Get("x-huru-api-token")
}
but I get this error:
anybody know what that's about?
The value nil
is not a valid value for a string
. If you want to fallback to the header on both missing values and empty values, then using the following code:
params := r.URL.Query()
tok := params.Get("x-huru-api-token")
if tok == "" {
tok = r.Header.Get("x-huru-api-token")
}
If you only want to fallback to the header when the query parameter is missing, then use the following:
params := r.URL.Query()
var tok string
if values, ok := params["x-huru-api-token"]; ok && len(values) > 0 {
tok = values[0] // note that tok can be the empty string ""
} else {
tok = r.Header.Get("x-huru-api-token")
}
Note one difference between the code in this answer and the question. This answer uses assignment to set tok
inside the if statement. The code in the question uses a short variable declaration. The short variable declaration will not compile because the newly declared variable inside the if statement is not used.
String is not a pointer type in Go therefore it cannot be nil
. Zero value for string is empty string ("").
The correct code should be:
params := r.URL.Query()
tok := params["x-huru-api-token"][0];
if tok == "" {
tok := r.Header.Get("x-huru-api-token")
}