Documentation
¶
Overview ¶
Package httpservertest holds helpers for testing handlers written against pkg/httpserver.
A handler that reads a path parameter with httpserver.GetParam depends on the chi route context, which only exists once the router has matched the request. Calling such a handler directly from a test - without a router - leaves the parameter empty. SetURLParam populates it:
req := httptest.NewRequest(http.MethodGet, "/orders/42", nil) httpservertest.SetURLParam(req, "id", "42") err := handleOrder(httptest.NewRecorder(), req)
SetURLParam mutates the request in place rather than returning a copy, so the variable already in hand carries the parameter.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func SetURLParam ¶
SetURLParam adds a chi path parameter to r, so a handler calling httpserver.GetParam finds it without a router having matched the request.
It mutates r in place.
Example ¶
Calling a handler directly, without a router, leaves path parameters empty because nothing has matched the route. SetURLParam fills them in.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/diegodesousas/go-devkit/pkg/httpserver"
"github.com/diegodesousas/go-devkit/pkg/httpserver/httpservertest"
)
func main() {
handler := func(w http.ResponseWriter, r *http.Request) error {
_, err := fmt.Fprintf(w, "order %q", httpserver.GetParam(r, "id"))
return err
}
req := httptest.NewRequest(http.MethodGet, "/orders/42", nil)
without := httptest.NewRecorder()
_ = handler(without, req)
fmt.Println(without.Body.String())
httpservertest.SetURLParam(req, "id", "42")
with := httptest.NewRecorder()
_ = handler(with, req)
fmt.Println(with.Body.String())
}
Output: order "" order "42"
Types ¶
This section is empty.