Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

170
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda