-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathservicemux.go
73 lines (63 loc) · 1.91 KB
/
servicemux.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
package main
import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
)
type ServiceMux struct {
service *Service
serveMux *http.ServeMux
internalProxy *httputil.ReverseProxy
}
func NewServiceMux(c *Config, s *Service, proxyDest string) *ServiceMux {
dest, _ := url.Parse(proxyDest)
r := &ServiceMux{service: s, internalProxy: NewSingleHostReverseProxy(c, dest)}
r.init()
return r
}
func (p *ServiceMux) init() {
p.serveMux = http.NewServeMux()
if p.service != nil {
p.serveMux.HandleFunc("/robots.txt", p.robots)
}
p.serveMux.Handle("/", p.internalProxy)
}
func (p *ServiceMux) robots(w http.ResponseWriter, r *http.Request) {
if p.service.config.Robots != "" {
fmt.Fprint(w, p.service.config.Robots)
} else {
fmt.Fprint(w, "User-agent: *\nDisallow: /")
}
}
func (p *ServiceMux) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
p.serveMux.ServeHTTP(rw, req)
}
func NewSingleHostReverseProxy(config *Config, target *url.URL) *httputil.ReverseProxy {
targetQuery := target.RawQuery
director := func(req *http.Request) {
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
if targetQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = targetQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
}
// FIXME : Nuxeo hack to be able to add a virtual-host header param.
// To be removed as soon as possible
if config.UrlHeaderParam != "" {
scheme := req.Header.Get("x-forwarded-proto")
host := req.Host
port := req.Header.Get("x-forwarded-port")
url := ""
if ("https" == scheme && "443" == port) || ("http" == scheme && "80" == port) {
url = fmt.Sprintf("%s://%s/", scheme, host)
} else {
url = fmt.Sprintf("%s://%s:%s/", scheme, host, port)
}
req.Header.Add(config.UrlHeaderParam, url)
}
}
return &httputil.ReverseProxy{Director: director}
}