2015-01-30 01:52:18 -05:00
|
|
|
// Package proxy is middleware that proxies requests.
|
2015-01-30 00:05:36 -05:00
|
|
|
package proxy
|
2015-01-29 19:17:59 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net/http"
|
2015-02-03 01:41:35 -05:00
|
|
|
"net/http/httputil"
|
|
|
|
"net/url"
|
2015-04-01 00:53:39 -05:00
|
|
|
"strings"
|
2015-01-30 00:05:36 -05:00
|
|
|
|
|
|
|
"github.com/mholt/caddy/middleware"
|
2015-01-29 19:17:59 -05:00
|
|
|
)
|
|
|
|
|
2015-01-30 00:05:36 -05:00
|
|
|
// New creates a new instance of proxy middleware.
|
|
|
|
func New(c middleware.Controller) (middleware.Middleware, error) {
|
2015-01-29 19:17:59 -05:00
|
|
|
var rules []proxyRule
|
|
|
|
|
2015-01-30 00:05:36 -05:00
|
|
|
for c.Next() {
|
2015-01-29 19:17:59 -05:00
|
|
|
rule := proxyRule{}
|
|
|
|
|
2015-01-30 00:05:36 -05:00
|
|
|
if !c.Args(&rule.from, &rule.to) {
|
|
|
|
return nil, c.ArgErr()
|
2015-01-29 19:17:59 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
rules = append(rules, rule)
|
|
|
|
}
|
|
|
|
|
2015-04-03 00:30:54 -05:00
|
|
|
return func(next middleware.Handler) middleware.Handler {
|
|
|
|
return middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
|
2015-01-29 19:17:59 -05:00
|
|
|
|
|
|
|
for _, rule := range rules {
|
2015-01-30 00:05:36 -05:00
|
|
|
if middleware.Path(r.URL.Path).Matches(rule.from) {
|
2015-04-01 00:53:39 -05:00
|
|
|
var base string
|
|
|
|
|
|
|
|
if strings.HasPrefix(rule.to, "http") { // includes https
|
|
|
|
// destination includes a scheme! no need to guess
|
|
|
|
base = rule.to
|
2015-02-03 01:41:35 -05:00
|
|
|
} else {
|
2015-04-01 00:53:39 -05:00
|
|
|
// no scheme specified; assume same as request
|
|
|
|
var scheme string
|
|
|
|
if r.TLS == nil {
|
|
|
|
scheme = "http"
|
|
|
|
} else {
|
|
|
|
scheme = "https"
|
|
|
|
}
|
|
|
|
base = scheme + "://" + rule.to
|
2015-02-03 01:41:35 -05:00
|
|
|
}
|
2015-01-29 19:17:59 -05:00
|
|
|
|
2015-04-01 00:53:39 -05:00
|
|
|
baseUrl, err := url.Parse(base)
|
2015-01-29 19:17:59 -05:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2015-02-03 01:41:35 -05:00
|
|
|
r.Host = baseUrl.Host
|
|
|
|
|
|
|
|
// TODO: Construct this before; not during every request, if possible
|
|
|
|
proxy := httputil.NewSingleHostReverseProxy(baseUrl)
|
|
|
|
proxy.ServeHTTP(w, r)
|
2015-03-28 17:56:56 -05:00
|
|
|
return 0, nil
|
2015-01-29 19:17:59 -05:00
|
|
|
}
|
|
|
|
}
|
2015-03-28 17:56:56 -05:00
|
|
|
|
2015-04-03 00:30:54 -05:00
|
|
|
return next.ServeHTTP(w, r)
|
|
|
|
})
|
2015-01-30 00:05:36 -05:00
|
|
|
}, nil
|
2015-01-29 19:17:59 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
type proxyRule struct {
|
|
|
|
from string
|
|
|
|
to string
|
|
|
|
}
|