0

I am creating a module which will provide a http.Handler that can be attached to any running server.

My module has a lot of bundled handlerFuncs for handling internal requests:

func NewHandler() http.Handler {
    mux := http.NewServeMux()
    mux.HandleFunc("/one", func(writer http.ResponseWriter, request *http.Request) {
        writer.Write([]byte("one"))
    })
    mux.HandleFunc("/two", func(writer http.ResponseWriter, request *http.Request) {
        writer.Write([]byte("two"))
    })
    return mux
}

This handler can be attached to a custom path:

package main

import (
    "net/http"

    "github.com/someuser/someproject"
)

func main() {
    http.Handle("/path", someproject.NewHandler())
    http.ListenAndServe(":8080", nil)
}

On request invocation to http://localhost:8080/path/one I get 404. What am I doing wrong?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
randomUser56789
  • 936
  • 2
  • 13
  • 32
  • 6
    You are missing the / at the end of path.. You need to [strip the path prefix](https://godoc.org/net/http#StripPrefix) passed to `NewHandler`. `http.Handle("/path/", http.StripPrefix("/path/", someproject.NewHandler())` – Charlie Tumahai Dec 05 '20 at 16:43
  • @CeriseLimón `http.Handle("/path/", http.StripPrefix("/path/", someproject.NewHandler()))`, the request redirects to `localhost:8080/one` and I get `404`. Also I can't remove base path and have a redirect to endpoint `/one` on root, because it can be already used by the host server for something else if someone uses my module. – randomUser56789 Dec 05 '20 at 17:41
  • 2
    What happens if you strip only `"/path"`? – mkopriva Dec 05 '20 at 18:04
  • 1
    @mkopriva Yes, thank you, that worked. Having `http.Handle("/path/", http.StripPrefix("/path", someproject.NewHandler()))` works as expected. Request return 200 without redirects and does not interfere if I define with the endpoint `http.HandleFunc("/one", ...` on the server – randomUser56789 Dec 05 '20 at 18:12
  • See [How to combine two (or more) http.ServeMux?](https://stackoverflow.com/a/43380025/5728991). Possible duplicate? –  Dec 05 '20 at 18:43

0 Answers0