0
Fork 0
mirror of https://github.com/caddyserver/caddy.git synced 2024-12-23 22:27:38 -05:00
caddy/middleware/proxy/proxy.go

71 lines
1.5 KiB
Go
Raw Normal View History

// Package proxy is middleware that proxies requests.
package proxy
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"
"github.com/mholt/caddy/middleware"
)
// New creates a new instance of proxy middleware.
func New(c middleware.Controller) (middleware.Middleware, error) {
var rules []proxyRule
for c.Next() {
rule := proxyRule{}
if !c.Args(&rule.from, &rule.to) {
return nil, c.ArgErr()
}
rules = append(rules, rule)
}
return func(next middleware.Handler) middleware.Handler {
return middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
for _, rule := range rules {
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-04-01 00:53:39 -05:00
baseUrl, err := url.Parse(base)
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)
return 0, nil
}
}
return next.ServeHTTP(w, r)
})
}, nil
}
type proxyRule struct {
from string
to string
}