-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhandler.go
99 lines (82 loc) · 2.29 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package awses
import (
"fmt"
"net/http"
"strings"
"github.com/aws/aws-sdk-go/aws/session"
)
type Handler struct {
Config *Config
manager *ElasticsearchManager
}
func NewHandler(config *Config, rootSession *session.Session) *Handler {
return &Handler{
Config: config,
manager: NewElasticsearchManager(rootSession, config.Role),
}
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
// parse the path
path := r.URL.Path
if path == "" {
path = "/"
}
region := h.Config.Region
if region == "" {
region, path = splitNextComponent(path)
}
domain := h.Config.Domain
if domain == "" {
domain, path = splitNextComponent(path)
}
// render the corresponding response
if region == "" {
return h.renderMissingRegion(w)
} else if domain == "" {
return h.renderMissingDomain(w, region)
} else {
return h.proxyRequest(w, r, region, domain, path)
}
}
func (h *Handler) renderMissingRegion(w http.ResponseWriter) (int, error) {
http.Error(w, "An AWS region must be provided", http.StatusBadRequest)
return 0, nil
}
func (h *Handler) renderMissingDomain(w http.ResponseWriter, region string) (int, error) {
domains, err := h.manager.ListDomains(region)
if err != nil {
http.Error(w, "An AWS ES domain name must be provided", http.StatusInternalServerError)
return 0, nil
}
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "An AWS ES domain name must be provided. Available domain names:\n\n")
for _, domain := range domains {
fmt.Fprintf(w, "%s\n", domain)
}
return 0, nil
}
func (h *Handler) proxyRequest(w http.ResponseWriter, r *http.Request, region, domain, path string) (int, error) {
reverseProxy, err := h.manager.GetProxy(region, domain)
if err != nil {
if err == ErrDomainNotFound {
http.Error(w, err.Error(), http.StatusNotFound)
} else if err == ErrInvalidDomainName {
http.Error(w, err.Error(), http.StatusBadRequest)
} else {
http.Error(w, err.Error(), http.StatusBadGateway)
}
return 0, err
}
r.URL.Path = path
reverseProxy.ServeHTTP(w, r)
return 0, nil
}
func splitNextComponent(path string) (string, string) {
split := strings.SplitN(strings.TrimLeft(path, "/"), "/", 2)
if len(split) == 2 {
return split[0], "/" + split[1]
} else {
return split[0], "/"
}
}