forked from gophercises/urlshort
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
71 lines (64 loc) · 1.92 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package urlshort
import (
"net/http"
"gopkg.in/yaml.v2"
)
// MapHandler will return an http.HandlerFunc (which also
// implements http.Handler) that will attempt to map any
// paths (keys in the map) to their corresponding URL (values
// that each key in the map points to, in string format).
// If the path is not provided in the map, then the fallback
// http.Handler will be called instead.
func MapHandler(pathsToUrls map[string]string, fallback http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if dest, ok := pathsToUrls[path]; ok {
http.Redirect(w, r, dest, http.StatusFound)
return
}
fallback.ServeHTTP(w, r)
}
}
// YAMLHandler will parse the provided YAML and then return
// an http.HandlerFunc (which also implements http.Handler)
// that will attempt to map any paths to their corresponding
// URL. If the path is not provided in the YAML, then the
// fallback http.Handler will be called instead.
//
// YAML is expected to be in the format:
//
// - path: /some-path
// url: https://www.some-url.com/demo
//
// The only errors that can be returned all related to having
// invalid YAML data.
//
// See MapHandler to create a similar http.HandlerFunc via
// a mapping of paths to urls.
func YAMLHandler(yamlBytes []byte, fallback http.Handler) (http.HandlerFunc, error) {
pathUrls, err := parseYaml(yamlBytes)
if err != nil {
return nil, err
}
pathsToUrls := buildMap(pathUrls)
return MapHandler(pathsToUrls, fallback), nil
}
func buildMap(pathUrls []pathUrl) map[string]string {
pathsToUrls := make(map[string]string)
for _, pu := range pathUrls {
pathsToUrls[pu.Path] = pu.URL
}
return pathsToUrls
}
func parseYaml(data []byte) ([]pathUrl, error) {
var pathUrls []pathUrl
err := yaml.Unmarshal(data, &pathUrls)
if err != nil {
return nil, err
}
return pathUrls, nil
}
type pathUrl struct {
Path string `yaml:"path"`
URL string `yaml:"url"`
}