Last active
February 19, 2021 21:07
-
-
Save jreisinger/abbcbe636197a76dadbd0a6d7a94c9eb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Pathresolver handles complex URL paths with wildcards. | |
package main | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
"path" | |
"strings" | |
) | |
func main() { | |
pr := newPathResolver() | |
pr.Add("GET /hello", hello) | |
pr.Add("* /goodbye/*", goodbye) | |
log.Fatal(http.ListenAndServe(":8080", pr)) | |
} | |
func newPathResolver() *pathResolver { | |
return &pathResolver{make(map[string]http.HandlerFunc)} | |
} | |
type pathResolver struct { | |
handlers map[string]http.HandlerFunc | |
} | |
func (p *pathResolver) Add(path string, handler http.HandlerFunc) { | |
p.handlers[path] = handler | |
} | |
func (p *pathResolver) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
check := r.Method + " " + r.URL.Path | |
for pattern, handlerFunc := range p.handlers { | |
if ok, err := path.Match(pattern, check); ok && err == nil { | |
handlerFunc(w, r) | |
return | |
} else if err != nil { | |
fmt.Fprint(w, err) | |
} | |
} | |
http.NotFound(w, r) | |
} | |
func hello(w http.ResponseWriter, r *http.Request) { | |
name := r.URL.Query().Get("name") | |
if name == "" { | |
name = "foo" | |
} | |
fmt.Fprint(w, "hello ", name) | |
} | |
func goodbye(w http.ResponseWriter, r *http.Request) { | |
name := strings.Split(r.URL.Path, "/")[2] | |
if name == "" { | |
name = "bar" | |
} | |
fmt.Fprint(w, "goodbye ", name) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment