Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

httprouter.ParamsWithContext(r.Context()) is returning [] #350

Open
samirprakash opened this issue May 24, 2022 · 1 comment
Open

httprouter.ParamsWithContext(r.Context()) is returning [] #350

samirprakash opened this issue May 24, 2022 · 1 comment

Comments

@samirprakash
Copy link

Using alice with httprouter to chain middleware and wrapping params before passing it to the middleware function.

func (s *Server) wrap(next http.Handler) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		ctx := context.WithValue(r.Context(), params, ps)
		next.ServeHTTP(w, r.WithContext(ctx))
	}
}
/ routes configure server API endpoints
func (s *Server) routes() http.Handler {
	r := httprouter.New()
	secure := alice.New(s.authenticateWithIDMS)

	// unsecured end points
	r.HandlerFunc(http.MethodGet, "/api/v2/projects/:id", s.getProject)

	// secured end points
	r.GET("/api/v2/projects/:id", s.wrap(secure.ThenFunc(s.getProject)))

	return s.enableCORS(r)
}
func (s *Server) enableCORS(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,PATCH")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")

		next.ServeHTTP(w, r)
	})
}
// getProject returns all the projects as an API response
func (s *Server) getProject(w http.ResponseWriter, r *http.Request) {
	params := httprouter.ParamsFromContext(r.Context())
	log.Println(params)

	id, err := strconv.Atoi(params.ByName("id"))
	if err != nil {
		s.logger.Println(errors.New("invalid movie id : "), err)
		utils.ErrorJSON(w, err)
		return
	}

	utils.WriteJSON(w, http.StatusOK, id, "data")
}

Inside getProjects(), r.Context().Value("params") returns [{id 1}] but httprouter.ParamsFromContext(r.Context()) returns [] when I use the s.wrap() call, but if I do not use it then the params are passed properly.

Any pointers?

@cerpmath123
Copy link

cerpmath123 commented Dec 3, 2024

What exactly is params in your wrap() function? Please provide a minimal working example to replicate the issue next time.

The issue you are facing is due to the wrong key you are passing as params in the wrap() function. httprouter.ParamsFromContext() expects to find the parameters with the key httprouter.ParamsKey. Here is a working version of your wrap() function:

func (s *Server) wrap(next http.Handler) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		ctx := context.WithValue(r.Context(), httprouter.ParamsKey, ps)
		next.ServeHTTP(w, r.WithContext(ctx))
	}
}

and here is a minimal working example

package main

import (
	"context"
	"errors"
	"fmt"
	"github.com/julienschmidt/httprouter"
	"github.com/justinas/alice"
	"log"
	"net/http"
	"strconv"
)

type Server struct {
}

func (s *Server) routes() http.Handler {
	r := httprouter.New()
	secure := alice.New()

	// unsecured end points
	r.HandlerFunc(http.MethodGet, "/api/v2/projects/:id", s.getProject)

	// secured end points
	r.GET("/api/v2/secure/projects/:id", s.wrap(secure.ThenFunc(s.getProject)))

	return alice.New().Then(r)
}

func (s *Server) getProject(w http.ResponseWriter, r *http.Request) {
	params := httprouter.ParamsFromContext(r.Context())
	fmt.Printf("Parameters: %s\n", params)

	id, err := strconv.Atoi(params.ByName("id"))
	if err != nil {
		log.Println(errors.New("invalid movie id : "), err)
		return
	}

	fmt.Printf("Id: %d\n", id)
}

func (s *Server) wrap(next http.Handler) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		ctx := context.WithValue(r.Context(), httprouter.ParamsKey, ps)
		next.ServeHTTP(w, r.WithContext(ctx))
	}
}

func main() {
	s := Server{}
	srv := &http.Server{
		Addr:    "localhost:8080",
		Handler: s.routes(),
	}

	err := srv.ListenAndServe()
	log.Fatal(err)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants