puppeteer701
puppeteer701

Reputation: 1285

httprouter panic: path must begin with '/' in path 'GET'

I am moving my handler from net/http / mux to httprouter and my tests are failing. I am doing a request to a server running in a separate go routine. httprouter is complaining that the path must start with /, not sure why.

httprouter implementation:

    mux := httprouter.New()
    mux.HandlerFunc("/api", http.MethodGet, wrapper(s.rootHandler()))

test calling the pth

    req, err := http.NewRequest(http.MethodGet, "http://localhost:8080/api", nil)
    req.Header.Set("Content-Type", "application/json")
    if err != nil {
        return err
    }
    res, err := http.DefaultClient.Do(req)
    if err != nil {
        return err
    }
    defer res.Body.Close() //nolint:errcheck
    if res.StatusCode != http.StatusOK {
        return errors.New("server not yet running")
    }

Not sure it is throwing a panic. It has no issues running with net/http mux.

Upvotes: 1

Views: 103

Answers (1)

meshkati
meshkati

Reputation: 2413

As @mkopriva mentioned, julienschmidt/httprouter Router.HandlerFunc(method, path string, handler http.HandlerFunc) takes the path as the second argument, as well as the method in the first argument.

But in the standard net/http Serve.HandleFunc(pattern string, handler http.HandlerFunc) we have the path as the first argument.

So change:

mux.HandlerFunc("/api", http.MethodGet, wrapper(s.rootHandler()))

into

mux.HandlerFunc(http.MethodGet, "/api", wrapper(s.rootHandler()))

Upvotes: 1

Related Questions