forked from nytimes/gcs-helper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
41 lines (38 loc) · 1.08 KB
/
map.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
package handlers
import (
"encoding/json"
"net/http"
"regexp"
"strings"
"cloud.google.com/go/storage"
"github.com/caseyh/gcs-helper/v3/vodmodule"
)
// Map returns the map handler.
func Map(c Config, client *storage.Client) http.Handler {
mapper := vodmodule.NewMapper(client.Bucket(c.BucketName))
filter := regexp.MustCompile(c.Map.RegexFilter)
logger := c.Logger()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
prefix := strings.TrimLeft(r.URL.Path, "/")
if prefix == "" {
http.Error(w, "prefix cannot be empty", http.StatusBadRequest)
return
}
m, err := mapper.Map(r.Context(), vodmodule.MapOptions{
Prefix: prefix,
Filter: filter,
})
if err != nil {
logger.WithError(err).WithField("prefix", prefix).Error("failed to map request")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(m)
})
}