Skip to content

Instantly share code, notes, and snippets.

@Daniel1984
Created April 25, 2020 14:43
Show Gist options
  • Save Daniel1984/c79cdf3fec43a17811eb7e993825afad to your computer and use it in GitHub Desktop.
Save Daniel1984/c79cdf3fec43a17811eb7e993825afad to your computer and use it in GitHub Desktop.
// cmd/api/handlers/getuser/validarequest.go
package getuser
import (
"context"
"fmt"
"net/http"
"strconv"
"github.com/boilerplate/cmd/api/models"
"github.com/julienschmidt/httprouter"
)
func validateRequest(next httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
uid := p.ByName("id")
id, err := strconv.Atoi(uid)
if err != nil {
w.WriteHeader(http.StatusPreconditionFailed)
fmt.Fprintf(w, "malformed id")
return
}
ctx := context.WithValue(r.Context(), models.CtxKey("userid"), id)
r = r.WithContext(ctx)
next(w, r, p)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment