2023-05-26 04:06:35 +04:00
|
|
|
package httpr
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type path []string
|
|
|
|
|
2023-09-05 05:58:29 +04:00
|
|
|
// newPath ensures that a path provided is correct and splits it.
|
2023-05-26 04:06:35 +04:00
|
|
|
func newPath(path string) (path, error) {
|
2023-09-05 05:58:29 +04:00
|
|
|
pathLen := len(path)
|
|
|
|
|
|
|
|
if pathLen == 0 {
|
|
|
|
return nil, errors.New("empty path is not allowed")
|
|
|
|
}
|
|
|
|
|
2023-05-28 01:22:28 +04:00
|
|
|
if path[0] != '/' {
|
2023-08-12 18:55:00 +04:00
|
|
|
return nil, errors.New("path should start with a slash symbol \"/\"")
|
2023-05-26 04:06:35 +04:00
|
|
|
}
|
2023-05-28 01:22:28 +04:00
|
|
|
|
|
|
|
if strings.Count(path, "*") > 1 {
|
2023-08-12 18:55:00 +04:00
|
|
|
return nil, errors.New("path can have only one catch-all parameter \"*\"")
|
2023-05-28 01:22:28 +04:00
|
|
|
}
|
|
|
|
|
2023-09-05 05:58:29 +04:00
|
|
|
if path[pathLen-1] == '/' {
|
|
|
|
path = path[:pathLen-1]
|
|
|
|
}
|
|
|
|
|
|
|
|
parts := strings.Split(path, "/")
|
|
|
|
|
|
|
|
parts[0] = "/"
|
|
|
|
|
|
|
|
return parts, nil
|
|
|
|
}
|
|
|
|
|
2023-07-23 23:19:58 +04:00
|
|
|
path = strings.ReplaceAll(path, "//", "/")
|
|
|
|
|
2023-05-28 01:22:28 +04:00
|
|
|
parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
|
|
|
|
|
2023-05-26 04:06:35 +04:00
|
|
|
parts[0] = "/"
|
2023-05-28 01:22:28 +04:00
|
|
|
|
2023-05-26 04:06:35 +04:00
|
|
|
return parts, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Params holds path parameters that are set as :key.
|
|
|
|
type Params map[string]string
|
|
|
|
|
|
|
|
type paramsKey struct{}
|
|
|
|
|
|
|
|
// ParamsKey is used as a key for Params in a request's Context.
|
|
|
|
var ParamsKey paramsKey = paramsKey{}
|
|
|
|
|
|
|
|
type node struct {
|
|
|
|
endpoint string
|
|
|
|
children []*node
|
|
|
|
handler http.HandlerFunc
|
|
|
|
}
|
|
|
|
|
2023-05-28 01:46:57 +04:00
|
|
|
func (n *node) get(path path) (http.HandlerFunc, Params) {
|
|
|
|
pathLen := len(path)
|
|
|
|
curNode := n
|
|
|
|
|
|
|
|
outer:
|
|
|
|
for i := range path {
|
|
|
|
// Check if this node is a catch-all endpoint.
|
|
|
|
if curNode.endpoint[0] == '*' {
|
|
|
|
var p Params = Params{}
|
|
|
|
p[curNode.endpoint[1:]] = strings.Join(path[i:], "/")
|
|
|
|
return curNode.handler, p
|
|
|
|
}
|
2023-05-26 04:06:35 +04:00
|
|
|
|
2023-05-28 01:46:57 +04:00
|
|
|
// If this is a parametrised endpoint, then add its name to
|
|
|
|
// a path's part. It will be used further to parse parameters.
|
|
|
|
if curNode.endpoint[0] == ':' {
|
|
|
|
path[i] = curNode.endpoint + ":" + path[i]
|
|
|
|
}
|
2023-05-26 04:06:35 +04:00
|
|
|
|
2023-05-28 01:46:57 +04:00
|
|
|
if pathLen == i+1 {
|
|
|
|
var params Params = make(Params)
|
2023-05-26 04:06:35 +04:00
|
|
|
|
2023-05-28 01:46:57 +04:00
|
|
|
for _, part := range path {
|
|
|
|
if part[0] == ':' {
|
|
|
|
param := strings.Split(part[1:], ":")
|
|
|
|
params[param[0]] = param[1]
|
|
|
|
}
|
2023-05-26 04:06:35 +04:00
|
|
|
}
|
|
|
|
|
2023-05-28 03:18:15 +04:00
|
|
|
return curNode.handler, params
|
2023-05-28 01:46:57 +04:00
|
|
|
}
|
2023-05-26 04:06:35 +04:00
|
|
|
|
2023-05-28 01:46:57 +04:00
|
|
|
if pathLen > i+1 {
|
|
|
|
var paramNode *node
|
2023-07-23 23:19:58 +04:00
|
|
|
if len(curNode.children) == 0 {
|
|
|
|
break outer
|
|
|
|
}
|
|
|
|
|
2023-05-28 03:18:15 +04:00
|
|
|
for _, next := range curNode.children {
|
2023-05-28 01:46:57 +04:00
|
|
|
if next.endpoint == path[i+1] {
|
|
|
|
curNode = next
|
|
|
|
continue outer
|
|
|
|
}
|
|
|
|
|
|
|
|
if next.endpoint[0] == ':' || next.endpoint[0] == '*' {
|
|
|
|
paramNode = next
|
|
|
|
}
|
2023-05-26 04:06:35 +04:00
|
|
|
}
|
|
|
|
|
2023-05-28 01:46:57 +04:00
|
|
|
if paramNode != nil {
|
|
|
|
curNode = paramNode
|
2023-08-11 18:45:17 +04:00
|
|
|
continue outer
|
2023-05-26 04:06:35 +04:00
|
|
|
}
|
2023-08-11 18:36:13 +04:00
|
|
|
|
|
|
|
break outer
|
2023-05-26 04:06:35 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
2023-05-28 01:46:57 +04:00
|
|
|
func (n *node) add(path path, handler http.HandlerFunc) error {
|
|
|
|
pathLen := len(path)
|
|
|
|
curNode := n
|
2023-05-26 04:06:35 +04:00
|
|
|
|
2023-05-28 01:46:57 +04:00
|
|
|
outer:
|
|
|
|
for i := range path {
|
|
|
|
if pathLen == i+1 {
|
|
|
|
if curNode.handler != nil {
|
|
|
|
return errors.New("attempt to redefine a handler for already existing path")
|
2023-05-26 04:06:35 +04:00
|
|
|
}
|
2023-05-28 01:46:57 +04:00
|
|
|
curNode.endpoint = path[i]
|
|
|
|
curNode.handler = handler
|
|
|
|
return nil
|
2023-05-26 04:06:35 +04:00
|
|
|
}
|
|
|
|
|
2023-05-28 02:43:09 +04:00
|
|
|
for _, child := range curNode.children {
|
2023-05-28 01:46:57 +04:00
|
|
|
firstChar := path[i+1][0]
|
|
|
|
if (firstChar == ':' || firstChar == '*') && firstChar == child.endpoint[0] {
|
2023-05-28 03:17:53 +04:00
|
|
|
// Do not allow different param names, because only the first one
|
|
|
|
// is saved, so a param won't be available by a new name.
|
2023-08-12 19:19:45 +04:00
|
|
|
// Therefore, it is good to return an error because in this case
|
|
|
|
// you're doing something wrong.
|
2023-05-28 03:17:53 +04:00
|
|
|
if path[i+1] != child.endpoint {
|
|
|
|
return errors.New("param names " + path[i+1] + " and " + child.endpoint + " are differ")
|
|
|
|
}
|
2023-05-28 01:46:57 +04:00
|
|
|
curNode = child
|
|
|
|
continue outer
|
|
|
|
}
|
|
|
|
|
|
|
|
if child.endpoint == path[i+1] {
|
|
|
|
curNode = child
|
|
|
|
continue outer
|
|
|
|
}
|
2023-05-26 04:06:35 +04:00
|
|
|
}
|
|
|
|
|
2023-05-28 01:46:57 +04:00
|
|
|
newChild := &node{endpoint: path[i+1]}
|
|
|
|
curNode.children = append(curNode.children, newChild)
|
|
|
|
curNode = newChild
|
|
|
|
}
|
2023-05-26 04:06:35 +04:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type Router struct {
|
|
|
|
tree map[string]*node
|
|
|
|
NotFoundHandler http.HandlerFunc
|
|
|
|
}
|
|
|
|
|
|
|
|
func New() *Router {
|
|
|
|
return &Router{tree: make(map[string]*node)}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rr *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2023-08-12 19:37:51 +04:00
|
|
|
tree, ok := rr.tree[r.Method]
|
|
|
|
if !ok {
|
|
|
|
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
|
|
|
|
return
|
|
|
|
}
|
2023-05-26 04:06:35 +04:00
|
|
|
|
2023-08-12 19:37:51 +04:00
|
|
|
path, err := newPath(r.URL.Path)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusNotAcceptable)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if handler, params := tree.get(path); handler != nil {
|
|
|
|
if params != nil {
|
|
|
|
r = r.WithContext(context.WithValue(r.Context(), ParamsKey, params))
|
2023-05-26 04:06:35 +04:00
|
|
|
}
|
2023-08-12 19:37:51 +04:00
|
|
|
handler(w, r)
|
2023-05-26 04:06:35 +04:00
|
|
|
} else {
|
2023-08-12 19:37:51 +04:00
|
|
|
if rr.NotFoundHandler != nil {
|
|
|
|
rr.NotFoundHandler(w, r)
|
|
|
|
} else {
|
|
|
|
http.Error(w, "Not Found", http.StatusNotFound)
|
|
|
|
}
|
2023-05-26 04:06:35 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Handler registers a handler for provided pattern for a given HTTP method.
|
2023-05-28 01:24:18 +04:00
|
|
|
func (rr *Router) Handler(method, pattern string, handler http.HandlerFunc) error {
|
|
|
|
path, err := newPath(pattern)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2023-05-26 04:06:35 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
if rr.tree[method] == nil {
|
|
|
|
rr.tree[method] = &node{endpoint: "/"}
|
|
|
|
}
|
|
|
|
|
2023-08-12 18:56:50 +04:00
|
|
|
return rr.tree[method].add(path, handler)
|
2023-05-26 04:06:35 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
// ServeStatic serves a given file system.
|
|
|
|
//
|
|
|
|
// Path should end with /*filepath to work.
|
2023-05-28 01:49:21 +04:00
|
|
|
func (rr *Router) ServeStatic(path string, root http.FileSystem) error {
|
2023-05-26 04:06:35 +04:00
|
|
|
fileServer := http.FileServer(root)
|
|
|
|
|
2023-05-28 01:49:21 +04:00
|
|
|
return rr.Handler(http.MethodGet, path, func(w http.ResponseWriter, r *http.Request) {
|
2023-05-26 04:06:35 +04:00
|
|
|
r.URL.Path = Param(r, "filepath")
|
|
|
|
fileServer.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-08-12 19:19:45 +04:00
|
|
|
// subPath attaches a base path in front of a pattern.
|
|
|
|
//
|
|
|
|
// It is not a sub-router, it just passes a resulted pattern down to
|
|
|
|
// a router instance.
|
2023-08-11 18:42:28 +04:00
|
|
|
type subPath struct {
|
|
|
|
r *Router
|
2023-08-12 19:19:04 +04:00
|
|
|
base string
|
2023-08-11 18:42:28 +04:00
|
|
|
}
|
|
|
|
|
2023-08-12 19:19:45 +04:00
|
|
|
// Sub creates a group of handlers with the same base path.
|
|
|
|
//
|
|
|
|
// How to use:
|
2023-08-11 18:42:28 +04:00
|
|
|
//
|
2023-08-12 19:19:45 +04:00
|
|
|
// r := httpr.New()
|
|
|
|
// ...
|
|
|
|
// s := r.Sub("/api/v1")
|
|
|
|
// s.Handler(http.MethodGet, "/", func(w, r) {...})
|
|
|
|
// s.Handler(http.MethodGet, "/section", func(w, r) {...})
|
2023-08-12 19:19:04 +04:00
|
|
|
func (rr *Router) Sub(base string) *subPath {
|
|
|
|
if base[len(base)-1] == '/' {
|
|
|
|
base = base[:len(base)-1]
|
2023-08-11 18:42:28 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
return &subPath{
|
|
|
|
r: rr,
|
2023-08-12 19:19:04 +04:00
|
|
|
base: base,
|
2023-08-11 18:42:28 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-12 19:19:45 +04:00
|
|
|
// Handler registers a handler for a sub-path.
|
2023-08-11 18:42:28 +04:00
|
|
|
func (sp *subPath) Handler(method, pattern string, handler http.HandlerFunc) error {
|
2023-08-12 19:19:04 +04:00
|
|
|
return sp.r.Handler(method, sp.base+pattern, handler)
|
2023-08-11 18:42:28 +04:00
|
|
|
}
|
|
|
|
|
2023-08-12 19:19:45 +04:00
|
|
|
// Param returns a URL parameter set with :key, or an empty string if not found.
|
2023-05-26 04:06:35 +04:00
|
|
|
func Param(r *http.Request, key string) string {
|
|
|
|
if params := r.Context().Value(ParamsKey).(Params); params != nil {
|
|
|
|
return params[key]
|
|
|
|
}
|
|
|
|
|
|
|
|
return ""
|
|
|
|
}
|