vendredi 26 mars 2021

Can't access mux params when testing API endpoint with custom handlers

I have a custom handler for my API endpoints like this:

type HTTPError struct {
    Error   error
    Message string
    Code    int
}

type endpointREST func(http.ResponseWriter, *http.Request) *HTTPError

func (fn endpointREST) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if e := fn(w, r); e != nil {
        http.Error(w, e.Message, e.Code)
    }
}

my example route look like this:

func GetShare(w http.ResponseWriter, r *http.Request) *HTTPError {
    vars := mux.Vars(r)
    fmt.Println(r.URL)  // http://127.0.0.1:36455/share/5713d228-a042-446d-a5e4-183b19fa832a
    fmt.Println(vars)  // -->> always empty map when testing 
    return nil
}

These routes work well (manual, using Postman) after setting them up with

router := mux.NewRouter().StrictSlash(true)
handler := cors.Default().Handler(router)
router.Handle("/share/{id}", endpointREST(GetShare)).Methods("GET")
log.Fatal(http.ListenAndServe(":6969", handler))

The Problem is, that i can't test the API this way, since mux.Vars(r) will always return an empty map in the testing environment.

This is my testing code:

func TestGetShare(t *testing.T) {
    Reset()
    router := mux.NewRouter()
    ts := httptest.NewServer(router)
    router.Handle("/share/{id}", endpointREST(GetShare)).Methods("GET")
    defer ts.Close()

    t.Run("unauthorized", func(t *testing.T) {
        req, _ := http.NewRequest("GET", ts.URL + "/share/5713d228-a042-446d-a5e4-183b19fa832a", nil)
        res, _ := http.DefaultClient.Do(req)
        assert.Equal(t, http.StatusUnauthorized, res.StatusCode)
    })
}

Aucun commentaire:

Enregistrer un commentaire