本文整理汇总了Golang中net/http/httputil.NewSingleHostReverseProxy函数的典型用法代码示例。如果您正苦于以下问题:Golang NewSingleHostReverseProxy函数的具体用法?Golang NewSingleHostReverseProxy怎么用?Golang NewSingleHostReverseProxy使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewSingleHostReverseProxy函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: NewMPSClient
// NewMPSClient constructs a MPSClient from the provided baseURL and
// TLS config.
// If TLS config is nil, the default configuration is used.
func NewMPSClient(baseURL string, tlsConfig *tls.Config) (*MPSClient, error) {
u, err := url.Parse(baseURL)
if err != nil {
return nil, fmt.Errorf("could not parse url: %v", err)
}
t := &http.Transport{TLSClientConfig: tlsConfig}
client := &http.Client{Transport: t}
if (u.Scheme != "http") && (u.Scheme != "https") {
return nil, fmt.Errorf("base url must have scheme 'http' or 'https'")
}
if u.Host == "" {
return nil, fmt.Errorf("no host in url")
}
var wsURL url.URL
wsURL = *u
wsURL.Scheme = "ws"
if u.Scheme == "https" {
wsURL.Scheme = "wss"
}
httpProxy := httputil.NewSingleHostReverseProxy(u)
wsProxy := wsutil.NewSingleHostReverseProxy(&wsURL)
httpProxy.Transport = t
wsProxy.TLSClientConfig = t.TLSClientConfig
return &MPSClient{baseURL, client, httpProxy, wsProxy, t}, nil
}
示例2: resolve
func (r *IoEtcdResolver) resolve(domainName string) (http.Handler, bool) {
domain := r.domains[domainName]
if domain != nil {
if domain.server == nil {
log.Printf("Building new HostReverseProxy for %s", domainName)
switch domain.typ {
case "iocontainer":
env := r.environments[domain.value]
uri := ""
if env.port != "80" {
uri = fmt.Sprintf("http://%s:%s/", env.ip, env.port)
} else {
uri = fmt.Sprintf("http://%s/", env.ip)
}
dest, _ := url.Parse(uri)
domain.server = httputil.NewSingleHostReverseProxy(dest)
case "uri":
dest, _ := url.Parse(domain.value)
domain.server = httputil.NewSingleHostReverseProxy(dest)
}
}
return domain.server, true
}
return nil, false
}
示例3: main
func main() {
if_bind = flag.String("interface", "127.0.0.1:3001", "server interface to bind")
apps_target = flag.String("apps", "http://127.0.0.1:8080", "target URL for apps reverse proxy")
management_target = flag.String("management", "http://127.0.0.1:8081", "target URL for management reverse proxy")
flag.Parse()
fmt.Printf("Interface: %v\n", *if_bind)
fmt.Printf("Apps-Url: %v\n", *apps_target)
fmt.Printf("Management-Url: %v\n", *management_target)
apps_target_url, _ := url.Parse(*apps_target)
management_target_url, _ := url.Parse(*management_target)
devices_target_url, _ := url.Parse("http://127.0.0.1:9200")
apps_proxy = newSwitchingProxy(apps_target_url)
management_proxy = httputil.NewSingleHostReverseProxy(management_target_url)
devices_proxy = httputil.NewSingleHostReverseProxy(devices_target_url)
go func() {
signal_chan := make(chan os.Signal, 10)
signal.Notify(signal_chan, syscall.SIGUSR1)
for true {
<-signal_chan
DEBUG = !DEBUG
fmt.Printf("Set debug to %v.\n", DEBUG)
}
}()
http.HandleFunc("/", defaultHandler)
err := http.ListenAndServe(*if_bind, nil)
if err != nil {
panic(err)
}
}
示例4: gateway
func gateway(request *restful.Request, response *restful.Response) {
log.Printf(request.HeaderParameter("API-Version"))
if request.HeaderParameter("API-Version") == "1.0" {
target, err := url.Parse("http://localhost:8008")
if err != nil {
log.Print(err)
return
}
c := httputil.NewSingleHostReverseProxy(target)
c.ServeHTTP(response.ResponseWriter, request.Request)
}
if request.HeaderParameter("API-Version") == "1.1" {
target, err := url.Parse("http://localhost:8008")
if err != nil {
log.Print(err)
return
}
c := httputil.NewSingleHostReverseProxy(target)
c.ServeHTTP(response.ResponseWriter, request.Request)
}
response.WriteErrorString(http.StatusNotFound, "404: Version not found!.")
}
示例5: New
// New creates a new Proxy
func New(detourURL string, defaultURL string) *Proxy {
dt, _ := url.Parse(detourURL)
df, _ := url.Parse(defaultURL)
return &Proxy{
detourProxy: httputil.NewSingleHostReverseProxy(dt),
defaultProxy: httputil.NewSingleHostReverseProxy(df),
}
}
示例6: main
func main() {
log.SetFlags(0)
log.SetPrefix("webxd: ")
mode := "web"
if len(os.Args) > 1 {
mode = os.Args[1]
}
switch mode {
case "web":
innerURL := &url.URL{Scheme: "http", Host: ":" + os.Getenv("PORT")}
rp := httputil.NewSingleHostReverseProxy(innerURL)
rp.Transport = new(WebsocketTransport)
http.Handle("/", LogHandler{rp})
http.HandleFunc("backend.webx.io/mon/ps", ListProc)
case "mon":
http.HandleFunc("backend.webx.io/mon/ps", ListProc)
}
if os.Getenv("WEBX_VERBOSE") != "" {
verbose = true
}
for {
err := webx.DialAndServeTLS(os.Getenv("WEBX_URL"), tlsConfig, nil)
if err != nil {
log.Println("DialAndServe:", err)
log.Println("DialAndServe:", os.Getenv("WEBX_URL"))
time.Sleep(redialPause)
}
}
}
示例7: createTcpHandler
func createTcpHandler(e string) http.Handler {
u, err := url.Parse(e)
if err != nil {
log.Fatal(err)
}
return httputil.NewSingleHostReverseProxy(u)
}
示例8: maybeProxyToLeader
func maybeProxyToLeader(w http.ResponseWriter, r *http.Request, body io.ReadCloser) {
leader := node.Leader()
if leader == "" {
http.Error(w, fmt.Sprintf("No leader known. Please try another server."),
http.StatusInternalServerError)
return
}
nodeProxiesMu.RLock()
p, ok := nodeProxies[leader]
nodeProxiesMu.RUnlock()
if !ok {
u, err := url.Parse("https://" + leader)
if err != nil {
http.Error(w, fmt.Sprintf("url.Parse(): %v", err), http.StatusInternalServerError)
return
}
p = httputil.NewSingleHostReverseProxy(u)
p.Transport = robusthttp.Transport(true)
// Races are okay, i.e. overwriting the proxy a different goroutine set up.
nodeProxiesMu.Lock()
nodeProxies[leader] = p
nodeProxiesMu.Unlock()
}
location := *r.URL
location.Host = leader
w.Header().Set("Content-Location", location.String())
log.Printf("Proxying request (%q) to leader %q\n", r.URL.Path, leader)
r.Body = body
p.ServeHTTP(w, r)
}
示例9: proxyToLeader
func (ms *MasterServer) proxyToLeader(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if ms.Topo.IsLeader() {
f(w, r)
} else if ms.Topo.GetRaftServer() != nil && ms.Topo.GetRaftServer().Leader() != "" {
ms.bounedLeaderChan <- 1
defer func() { <-ms.bounedLeaderChan }()
targetUrl, err := url.Parse("http://" + ms.Topo.GetRaftServer().Leader())
if err != nil {
writeJsonError(w, r, http.StatusInternalServerError,
fmt.Errorf("Leader URL http://%s Parse Error: %v", ms.Topo.GetRaftServer().Leader(), err))
return
}
glog.V(4).Infoln("proxying to leader", ms.Topo.GetRaftServer().Leader())
proxy := httputil.NewSingleHostReverseProxy(targetUrl)
director := proxy.Director
proxy.Director = func(req *http.Request) {
actualHost, err := security.GetActualRemoteHost(req)
if err == nil {
req.Header.Set("HTTP_X_FORWARDED_FOR", actualHost)
}
director(req)
}
proxy.Transport = util.Transport
proxy.ServeHTTP(w, r)
} else {
//drop it to the floor
//writeJsonError(w, r, errors.New(ms.Topo.RaftServer.Name()+" does not know Leader yet:"+ms.Topo.RaftServer.Leader()))
}
}
}
示例10: NewOauthProxy
func NewOauthProxy(proxyUrls []*url.URL, clientID string, clientSecret string, validator func(string) bool) *OauthProxy {
login, _ := url.Parse("https://accounts.google.com/o/oauth2/auth")
redeem, _ := url.Parse("https://accounts.google.com/o/oauth2/token")
info, _ := url.Parse("https://www.googleapis.com/oauth2/v2/userinfo")
serveMux := http.NewServeMux()
for _, u := range proxyUrls {
path := u.Path
u.Path = ""
log.Printf("mapping %s => %s", path, u)
serveMux.Handle(path, httputil.NewSingleHostReverseProxy(u))
}
return &OauthProxy{
CookieKey: "_oauthproxy",
CookieSeed: *cookieSecret,
Validator: validator,
clientID: clientID,
clientSecret: clientSecret,
oauthScope: "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",
oauthRedemptionUrl: redeem,
oauthLoginUrl: login,
oauthUserInfoUrl: info,
serveMux: serveMux,
}
}
示例11: newEndpoint
func newEndpoint(urlstr string) (*endpoint, error) {
u, err := url.Parse(urlstr)
if err != nil {
return nil, err
}
return &endpoint{httputil.NewSingleHostReverseProxy(u), urlstr}, nil
}
示例12: authAndProxyHandler
func authAndProxyHandler(auth hmacauth.HmacAuth, upstream *HmacProxyURL) (
handler http.Handler, description string) {
description = "proxying authenticated requests to: " + upstream.Raw
proxy := httputil.NewSingleHostReverseProxy(upstream.URL)
handler = authHandler{auth, proxy}
return
}
示例13: main
// Right now, this is a really simple proxy that uses defaults
// nearly everywhere, and does nothing other than blindly proxy a
// request to a single server.
func main() {
bind, provided := os.LookupEnv("BIND_ADDR")
if !provided {
bind = ":8090"
}
log.Println("Binding to", bind)
proxyHost, provided := os.LookupEnv("PROXY_ADDR")
if !provided {
proxyHost = "127.0.0.1:8080"
}
log.Println("Proxying host", proxyHost)
proxyPath, provided := os.LookupEnv("PROXY_PATH")
if !provided {
proxyPath = "/"
}
log.Println("Proxy Path", proxyPath)
proxy := httputil.NewSingleHostReverseProxy(&url.URL{Host: proxyHost, Path: proxyPath, Scheme: "http"})
if err := http.ListenAndServe(bind, proxy); err != nil {
log.Panic("Could not start proxy", err)
}
}
示例14: slaveProxyHandler
// slaveProxyHandler redirects to current master
func slaveProxyHandler(w http.ResponseWriter, r *http.Request) {
log.Infof("proxy handler for %q ", r.URL.Path)
localIP, err := getLocalAddr()
if err != nil {
log.Fatalf("Error getting local IP address. Err: %v", err)
}
// get current holder of master lock
masterNode := leaderLock.GetHolder()
if masterNode == "" {
http.Error(w, "Leader not found", http.StatusInternalServerError)
return
}
// If we are the master, return
if localIP == masterNode {
http.Error(w, "Self proxying error", http.StatusInternalServerError)
return
}
// build the proxy url
url, _ := url.Parse(fmt.Sprintf("http://%s:9999", masterNode))
// Create a proxy for the URL
proxy := httputil.NewSingleHostReverseProxy(url)
// modify the request url
newReq := *r
// newReq.URL = url
// Serve http
proxy.ServeHTTP(w, &newReq)
}
示例15: ServeHTTP
// ServeHTTP is basically a no-op unless an ACME challenge is active on this host
// and the request path matches the expected path exactly.
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
// Only if challenge is active
// TODO: this won't work until the global challenge hook in the acme package is ready
//if atomic.LoadInt32(&h.ChallengeActive) == 1 {
// Proxy challenge requests to ACME client
if strings.HasPrefix(r.URL.Path, challengeBasePath) {
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
hostname, _, err := net.SplitHostPort(r.URL.Host)
if err != nil {
hostname = r.URL.Host
}
upstream, err := url.Parse(scheme + "://" + hostname + ":" + alternatePort)
if err != nil {
return http.StatusInternalServerError, err
}
proxy := httputil.NewSingleHostReverseProxy(upstream)
proxy.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // client uses self-signed cert
}
proxy.ServeHTTP(w, r)
return 0, nil
}
//}
return h.Next.ServeHTTP(w, r)
}