Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!