Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
Auth token not being returned in middleware handler

I'm trying to write a function that checks my header for an auth token and also my db for if it exists. Problem is, I keep this mongo: no documents in result error.

This is what checks for the header.

func APIAuth(endpoint func(http.ResponseWriter, *http.Request)) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        accessToken := r.Header.Get("x-api-key")

        // Check token in db
        usersCollection := client.Database("cities-nighthack").Collection("users")
        filter := bson.D{
            primitive.E{
                Key: "token", Value: accessToken,
            },
        }

        var user User
        err := usersCollection.FindOne(context.TODO(), filter).Decode(&user)
        if err != nil {
            log.Fatal(err)
            http.Error(w, `Unauthorized access`, http.StatusUnauthorized)
        } else {
            // next.ServeHTTP(w, r)
            endpoint(w, r)
        }
    })
}

The route within main calls the handler like so

r.Handle("/suggest", APIAuth(searchCity)).Methods("GET")

The User struct is formatted as such:

type User struct {
    Email       string `json:"email"`
    AccessToken string `json:"token"`
}

Headers for Postman GET request

The headers in my postman request look like this

I know for a fact that the token exists in the db, so am I checking the header wrong or something?

over 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda