52 lines
1.1 KiB
Go
52 lines
1.1 KiB
Go
package server
|
|
|
|
import (
|
|
"local/rproxy3/storage/packable"
|
|
"log"
|
|
"net/http"
|
|
"net/http/httputil"
|
|
"net/url"
|
|
"strings"
|
|
)
|
|
|
|
type redirPurge struct {
|
|
proxyHost string
|
|
targetHost string
|
|
}
|
|
|
|
func (s *Server) Proxy(w http.ResponseWriter, r *http.Request) {
|
|
newURL, err := s.lookup(r.Host)
|
|
transport := &redirPurge{
|
|
proxyHost: r.Host,
|
|
targetHost: newURL.Host,
|
|
}
|
|
if err != nil {
|
|
http.NotFound(w, r)
|
|
log.Printf("unknown host lookup %q", r.Host)
|
|
return
|
|
}
|
|
r.Host = newURL.Host
|
|
proxy := httputil.NewSingleHostReverseProxy(newURL)
|
|
proxy.Transport = transport
|
|
proxy.ServeHTTP(w, r)
|
|
}
|
|
|
|
func (s *Server) lookup(host string) (*url.URL, error) {
|
|
host = strings.Split(host, ".")[0]
|
|
host = strings.Split(host, ":")[0]
|
|
v := packable.NewURL()
|
|
err := s.db.Get(nsRouting, host, v)
|
|
return v.URL(), err
|
|
}
|
|
|
|
func (rp *redirPurge) RoundTrip(r *http.Request) (*http.Response, error) {
|
|
resp, err := http.DefaultTransport.RoundTrip(r)
|
|
if err != nil {
|
|
return resp, err
|
|
}
|
|
if loc := resp.Header.Get("Location"); loc != "" {
|
|
resp.Header.Set("Location", strings.Replace(loc, rp.targetHost, rp.proxyHost, 1))
|
|
}
|
|
return resp, err
|
|
}
|