https://github.com/pierreprinetti/go-methodmux
A method-aware HTTP request multiplexer based on net/http
https://github.com/pierreprinetti/go-methodmux
http http-method mux server
Last synced: about 1 year ago
JSON representation
A method-aware HTTP request multiplexer based on net/http
- Host: GitHub
- URL: https://github.com/pierreprinetti/go-methodmux
- Owner: pierreprinetti
- License: mit
- Created: 2018-03-10T14:44:25.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2018-03-10T17:12:07.000Z (about 8 years ago)
- Last Synced: 2025-01-22T23:34:08.340Z (over 1 year ago)
- Topics: http, http-method, mux, server
- Language: Go
- Homepage:
- Size: 9.77 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Methodmux
[](http://godoc.org/github.com/pierreprinetti/go-methodmux)
[](https://travis-ci.org/pierreprinetti/go-methodmux)
[](https://goreportcard.com/report/github.com/pierreprinetti/go-methodmux)
[](https://coveralls.io/github/pierreprinetti/go-methodmux?branch=master)
Methodmux is a method-aware HTTP router based on net/http.
Methodmux exposes a single type: `ServeMux`. `ServeMux` holds a separate `http.ServeMux` for every HTTP verb an http.Handler has been registered to.
Every new request will be matched against the underlying `http.ServeMux` that corresponds to the HTTP method of the request.
If no match is found, `ServeMux` will look for a match in the other HTTP verbs. If a match is found, an HTTP code 405 "Method Not Allowed" is returned. If not, an HTTP code 404 "Not Found" is returned.
Methodmux has been written with readability in mind and is just as fast and efficient as `net/http` is.
## API
* `func New() *ServeMux`: allocates and returns a new ServeMux.
* `func (mux *ServeMux) Handle(method, pattern string, handler http.Handler)`: registers the handler for the given method and pattern.
* `func (mux *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)`: dispatches the request to the handler registered with the HTTP method of the request, and whose pattern most closely matches the request URL.
## Usage
```Go
package main
import (
"net/http"
methodmux "github.com/pierreprinetti/go-methodmux"
)
func main() {
mux := methodmux.New()
mux.Handle(http.MethodGet, "/some-endpoint/", getHandler)
mux.Handle("MYMETHOD", "/some-endpoint/", myMethodHandler)
mux.HandleFunc(http.MethodPost, "/some-endpoint/", func(rw http.ResponseWriter, req *http.Request) {
fmt.Fprintf(rw, "Hi! This the response to a POST call.")
})
srv := &http.Server{
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Fatal(srv.ListenAndServe())
}
```
Use godoc for more detailed documentation.