I am trying the authentication example and for some reason, I am unable to get key-values in the context object. Here is a sample code
package auth
import (
"context"
"net/http"
)
var userCtxKey = &contextKey{"user"}
type contextKey struct {
name string
}
type User struct {
Username string
}
func Middleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := User {
Username: "jon_snow",
}
// put it in context
ctx := context.WithValue(r.Context(), userCtxKey, user)
// and call the next with our new context
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
}
// ForContext finds the user from the context. REQUIRES Middleware to have run.
func ForContext(ctx context.Context) *User {
raw, _ := ctx.Value(userCtxKey).(*User)
return raw
}
package main
import (
"github.com/99designs/gqlgen/handler"
"github.com/go-chi/chi"
"gitlab.com/johnsnow/as"
"gitlab.com/johnsnow/as/middleware"
"log"
"net/http"
"os"
)
const defaultPort = "8080"
func main() {
port := os.Getenv("PORT")
if port == "" {
port = defaultPort
}
router := chi.NewRouter()
// Inject middleware
router.Use(auth.Middleware())
router.Handle("/", handler.Playground("GraphQL playground", "/query"))
router.Handle("/query",
handler.GraphQL(as.NewExecutableSchema(as.Config{Resolvers: &as.Resolver{}})))
log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
err := http.ListenAndServe(":"+port, router)
if err != nil {
panic(err)
}
}
func (r *mutationResolver) CreateRecord(ctx context.Context, input NewRecord) (models.Record, error) {
fmt.Printf(auth.ForContext(ctx))
return models.Record, nil
}
It should print jon_snow when CreateRecord mutation is executed
But it printed <nil>
Am I missing something ?
Is your problem that you are putting a User struct into context but then trying to get out a *User? If you check the type assertion return value in ForContext I suspect you will find an error and nil is just the empty value being returned.
Most helpful comment
Is your problem that you are putting a
Userstruct into context but then trying to get out a*User? If you check the type assertion return value inForContextI suspect you will find an error andnilis just the empty value being returned.