8

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:

enter image description here

anybody know what that's about?

1
  • 2
    nil is not a valid string type value, hence you cannot compare with it. Commented Dec 19, 2018 at 22:22

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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")
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.