https://github.com/acoshift/prefixhandler
Path Prefix Handler
https://github.com/acoshift/prefixhandler
golang handler
Last synced: about 2 months ago
JSON representation
Path Prefix Handler
- Host: GitHub
- URL: https://github.com/acoshift/prefixhandler
- Owner: acoshift
- License: mit
- Created: 2018-03-14T07:37:19.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2018-03-14T15:21:29.000Z (over 8 years ago)
- Last Synced: 2025-08-13T16:54:23.980Z (10 months ago)
- Topics: golang, handler
- Language: Go
- Size: 2.93 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# prefixhandler
[](https://travis-ci.org/acoshift/prefixhandler)
[](https://coveralls.io/github/acoshift/prefixhandler?branch=master)
[](https://goreportcard.com/report/github.com/acoshift/prefixhandler)
[](https://godoc.org/github.com/acoshift/prefixhandler)
Path Prefix Handler for http.ServeMux
## Example
```go
package main
import (
"io"
"net/http"
"github.com/acoshift/prefixhandler"
)
func main() {
mux := http.NewServeMux()
itemMux := http.NewServeMux()
itemMux.Handle("/", http.HandlerFunc(itemDetail))
itemMux.Handle("/edit", http.HandlerFunc(itemEdit))
mux.Handle("/item", http.NotFoundHandler())
mux.Handle("/item/", prefixhandler.New("/item", "item_id", itemMux))
http.ListenAndServe(":8080", mux)
}
func itemDetail(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
itemID := prefixhandler.Get(r.Context(), "item_id")
// or
// itemID = r.Context().Value("item_id").(string)
if itemID == "" {
http.NotFound(w, r)
return
}
io.WriteString(w, "Item: "+itemID)
}
func itemEdit(w http.ResponseWriter, r *http.Request) {
itemID := prefixhandler.Get(r.Context(), "item_id")
io.WriteString(w, "Editing Item: "+itemID)
}
```