Example #1
1
// 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
}
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
}
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)
	}
}
Example #4
0
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!.")
}
Example #5
0
// 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),
	}
}
Example #6
0
File: main.go Project: kr/webx
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)
		}
	}
}
Example #7
0
func createTcpHandler(e string) http.Handler {
	u, err := url.Parse(e)
	if err != nil {
		log.Fatal(err)
	}
	return httputil.NewSingleHostReverseProxy(u)
}
Example #8
0
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)
}
Example #9
0
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()))
		}
	}
}
Example #10
0
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,
	}
}
Example #11
0
func newEndpoint(urlstr string) (*endpoint, error) {
	u, err := url.Parse(urlstr)
	if err != nil {
		return nil, err
	}
	return &endpoint{httputil.NewSingleHostReverseProxy(u), urlstr}, nil
}
Example #12
0
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
}
Example #13
0
// 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)
	}
}
Example #14
0
// 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)
}
Example #15
0
// 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)
}
Example #16
0
// NewBackend creates and starts the named backend.
// The backend will be assigned a port using AllocatePort, and
// the process will be launched.
//
// If the port cannot be allocated or any error occurs in the startup, it
// is returned as err.
func (m *BackendManager) NewBackend(name string) (b *Backend, err error) {
	m.Lock()
	port, err := m.reallyAllocatePort()
	if err != nil {
		m.Unlock()
		return
	}
	b = &Backend{
		Name:    name,
		Port:    port,
		LastReq: time.Now(),
		notify:  m.notify,
	}
	m.backends[name] = b
	m.Unlock()

	buf := &bytes.Buffer{}
	err = m.proxyPrefix.Execute(buf, b)
	if err != nil {
		return
	}
	rawurl := string(buf.Bytes())
	b.url, err = url.Parse(rawurl)
	if err != nil {
		return
	}
	fmt.Printf("making new instance %s on port %d with backend url %s\n", name, b.Port, rawurl)

	b.proxy = httputil.NewSingleHostReverseProxy(b.url)

	go b.Start(m.config.InitCommand)
	return
}
Example #17
0
File: proxy.go Project: Zerak/micro
func (p *proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	service, err := p.getService(r)
	if err != nil {
		w.WriteHeader(500)
		return
	}

	if len(service) == 0 {
		w.WriteHeader(404)
		return
	}

	if isWebSocket(r) && p.ws {
		p.serveWebSocket(service, w, r)
		return
	}

	rp, err := url.Parse(service)
	if err != nil {
		w.WriteHeader(500)
		return
	}

	httputil.NewSingleHostReverseProxy(rp).ServeHTTP(w, r)
}
Example #18
0
func main() {
	flag.Parse()

	os.Setenv("PORT", fmt.Sprintf("%d", port+1))

	if err := command("Building client", "client", "npm", "run", "build").Run(); err != nil {
		log.Fatal("Failed to build client")
	}

	if err := command("Starting client", "client", "npm", "run", "serve").Start(); err != nil {
		log.Fatalf("Failed to start client %v", err)
	}

	var proxy *httputil.ReverseProxy
	if clientURL, err := url.Parse(fmt.Sprintf("http://localhost:%d", port+1)); err == nil {
		proxy = httputil.NewSingleHostReverseProxy(clientURL)
	} else {
		log.Fatalf("Failed to start client %v", err)
	}

	host := fmt.Sprintf("%s:%d", binding, port)
	log.Printf("Starting at %s", host)

	http.Handle("/", proxy)
	http.Handle("/api/", messageAPI)

	if err := http.ListenAndServe(host, nil); err != nil {
		log.Fatalf("Server error: %v", err)
	}
	log.Printf("Stopping %s", host)
}
Example #19
0
func (r *EnvResolver) getOrCreateProxyFor(uri string) http.Handler {
	if _, ok := r.dest2ProxyCache[uri]; !ok {
		dest, _ := url.Parse(uri)
		r.dest2ProxyCache[uri] = httputil.NewSingleHostReverseProxy(dest)
	}
	return r.dest2ProxyCache[uri]
}
Example #20
0
// POST /nodes/restart or POST /nodes/die or POST /nodes/id/resize/new-size
func (this ProxyNodeController) Act(rw http.ResponseWriter, parts []string, r *http.Request) {
	if CheckApiKey(this.apikey, r) == false {
		http.Error(rw, "api key required in header", http.StatusForbidden)
		return
	}

	if parts[0] == "restart" {
		go RestartIn(10)
	}
	if parts[0] == "die" {
		go DieIn(10)
	}

	preq, err := http.NewRequest(r.Method, r.URL.Path, r.Body)
	if err != nil {
		http.Error(rw, err.Error(), http.StatusBadRequest)
		return
	}

	preq.Header.Set("x-golem-apikey", this.apikey)

	logger.Debug("proxying %v to %v", r.URL.Path, this.target)
	proxy := httputil.NewSingleHostReverseProxy(this.target)
	proxy.ServeHTTP(rw, preq)
}
Example #21
0
// Set up Reverse Proxy
func ReverseProxy(rawurl string) http.Handler {
	u, err := url.Parse(rawurl)
	if err != nil {
		panic(err)
	}
	return httputil.NewSingleHostReverseProxy(u)
}
Example #22
0
// rProxy is a single host reverse proxy implementation
// See github.com/peteretelej/rproxy
func rProxy(listenAddr, remoteHost, scheme string) {
	http.HandleFunc("/",
		func(w http.ResponseWriter, r *http.Request) {
			session, err := store.Get(r, "sess")
			if err != nil {
				// compromised cookie?
				http.Error(w, err.Error(), 500)
				return
			}
			var allow, resetsess bool
			var wait string
			sid, exists := session.Values["sessid"]
			if exists {
				if val, ok := sid.(int); ok {
					allow, err = isAllowed(val)
					if err != nil {
						// not allowed and not waiting
						delete(session.Values, "sessid")
						resetsess = true
					} else {
						if !allow {
							// client already waiting, get wait time
							wait = getWait(val)
						}
					}
				} else {
					http.Error(w, "User SessionID not int", 500)
					return
				}
			} else {
				// No session ID exists (new user)
				resetsess = true
			}
			// Reset user session, either new user or
			// User with and retired session
			if resetsess {
				id, allowed := handleNew()
				session.Values["sessid"] = id
				allow = allowed
				if !allowed {
					// get wait time if new session was set to wait
					wait = getWait(id)
				}
			}
			session.Save(r, w)

			// Handle waiting user, notify when they can access
			if !allow {
				w.Write([]byte("Please try again later at: " + wait))
				return
			}
			p := httputil.NewSingleHostReverseProxy(&url.URL{
				Scheme: scheme,
				Host:   remoteHost,
			})
			p.ServeHTTP(w, r)

		})
	log.Fatal(http.ListenAndServe(listenAddr, context.ClearHandler(http.DefaultServeMux)))
}
Example #23
0
func main() {
	flag.Parse()

	if base == nil || *base == "" {
		fmt.Printf("you must specify the 'base' flag, re-run the program with: -base='http://mytargethost.com'\n")
		return
	}
	if host == nil || *host == "" {
		fmt.Printf("you must specify the 'host' flag, re-run the program with: -host=':80'\n")
		return
	}

	baseUrl, err := url.Parse(*base)
	if err != nil {
		fmt.Printf("invalid target value %v, %v", *baseUrl, err)
		return
	}

	fmt.Printf("hosting proxy at %v\n", *host)
	proxy := httputil.NewSingleHostReverseProxy(baseUrl)
	http.DefaultTransport = &http.Transport{MaxIdleConnsPerHost: 5000}
	if err := http.ListenAndServe(*host, proxy); err != nil {
		fmt.Printf("fatal: %v\n", err)
	}
}
Example #24
0
func ExampleReverseProxy() {
	backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "this call was relayed by the reverse proxy")
	}))
	defer backendServer.Close()

	rpURL, err := url.Parse(backendServer.URL)
	if err != nil {
		log.Fatal(err)
	}
	frontendProxy := httptest.NewServer(httputil.NewSingleHostReverseProxy(rpURL))
	defer frontendProxy.Close()

	resp, err := http.Get(frontendProxy.URL)
	if err != nil {
		log.Fatal(err)
	}

	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s", b)

	// Output:
	// this call was relayed by the reverse proxy
}
Example #25
0
func (p *Proxy) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	if ShuttingDown() {
		http.Error(w, "shutting down", http.StatusServiceUnavailable)
		return
	}

	target := GetTable().lookup(req, req.Header.Get("trace"))
	if target == nil {
		log.Print("[WARN] No route for ", req.URL)
		w.WriteHeader(404)
		return
	}

	if p.cfg.ClientIPHeader != "" {
		ip, _, err := net.SplitHostPort(req.RemoteAddr)
		if err != nil {
			http.Error(w, "cannot parse "+req.RemoteAddr, http.StatusInternalServerError)
			return
		}
		req.Header.Set(p.cfg.ClientIPHeader, ip)
	}

	if p.cfg.TLSHeader != "" && req.TLS != nil {
		req.Header.Set(p.cfg.TLSHeader, p.cfg.TLSHeaderValue)
	}

	start := time.Now()
	rp := httputil.NewSingleHostReverseProxy(target.URL)
	rp.Transport = p.tr
	rp.ServeHTTP(w, req)
	target.timer.UpdateSince(start)
	p.requests.UpdateSince(start)
}
Example #26
0
func main() {
	flag.Parse()
	goquic.SetLogLevel(logLevel)

	if flag.NArg() != 1 {
		flag.Usage()
		return
	}

	proxyUrl := flag.Arg(0)

	log.Printf("About to listen on %d. Go to https://127.0.0.1:%d/", port, port)
	portStr := fmt.Sprintf(":%d", port)

	parsedUrl, err := url.Parse(proxyUrl)
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Starting reverse proxy for backend URL: %v", parsedUrl)

	err = goquic.ListenAndServe(portStr, cert, key, numOfServers, httputil.NewSingleHostReverseProxy(parsedUrl))
	if err != nil {
		log.Fatal(err)
	}
}
Example #27
0
func Startup() {

	templating.Setup()

	mux := httprouter.New()

	for path := range PathMapForGet {
		mux.GET(path, PathMapForGet[path])
	}
	for path := range PathMapForPost {
		mux.POST(path, PathMapForPost[path])
	}

	// handle static files
	mux.ServeFiles("/assets/*filepath", http.Dir(config.PATH_BASE_GOLANG_ASSETS))

	var u *url.URL
	var err error
	u, err = url.Parse(config.BACK_END_URL)
	if err != nil {
		log.Fatal(err)
	}
	// handle reserve proxy
	proxy := handler(httputil.NewSingleHostReverseProxy(u))

	// set GET paths
	for _, path := range ProxyPathListForGet {
		mux.HandlerFunc("GET", path, proxy)
	}

	// set POST paths
	for _, path := range ProxyPathListForPost {
		mux.HandlerFunc("POST", path, proxy)
	}

	secureMiddleware := secure.New(secure.Options{
		SSLRedirect: true,
		SSLHost:     config.HOST,
	})
	app := authenticationHandler(secureMiddleware.Handler(mux))

	log.Println("Starting...")

	models.DbMap = initDbMap()
	defer models.DbMap.Close()
	err = models.DbMap.Ping()
	if err != nil {
		log.Fatal("ping:", err)
	}

	// HTTP
	go func() {
		log.Fatal(http.ListenAndServe(config.PORT_HTTP, mux))
	}()

	// HTTPS

	log.Fatal(http.ListenAndServeTLS(config.PORT_HTTPS, config.PATH_BASE_GOLANG_CERT+"/cert.pem", config.PATH_BASE_GOLANG_CERT+"/key.pem", app))

}
Example #28
0
func NewBackendList(backends ...Backend) (BackendList, int, error) {
	var (
		bl        BackendList
		maxWeight int
	)
	for _, backend := range backends {
		u, err := url.Parse(backend.Host)
		if err != nil {
			return bl, maxWeight, err
		}
		if backend.Weight == 0 {
			backend.Weight = DefaultWeight
		}
		if backend.Weight > maxWeight {
			maxWeight = backend.Weight
		}
		rp := httputil.NewSingleHostReverseProxy(u)
		if backend.FailTimeout == 0 {
			backend.FailTimeout = DefaultTimeout
		}
		rp.Transport = &http.Transport{
			Proxy: http.ProxyFromEnvironment,
			Dial: (&net.Dialer{
				Timeout:   backend.FailTimeout,
				KeepAlive: 30 * time.Second,
			}).Dial,
			TLSHandshakeTimeout: 10 * time.Second,
		}
		bl = append(bl, &BackendProxy{
			target: u,
			server: rp,
		})
	}
	return bl, maxWeight, nil
}
func main() {
	jenkins_address := os.Getenv("JENKINS_URL")
	listen_address := os.Getenv("LISTEN_ADDRESS")

	if listen_address == "" {
		listen_address = "[::]:8080"
	}
	if jenkins_address == "" {
		log.Fatalln("Use environment variables JENKINS_URL and LISTEN_ADDRESS (default \"[::]:8080\")")
	}

	remote, err := url.Parse(jenkins_address)
	if err != nil {
		log.Panic(err)
	}

	proxy := httputil.NewSingleHostReverseProxy(remote)
	http.HandleFunc("/", handler(proxy))

	log.Println("jenkins-authentication-proxy", version, "starting")
	log.Println("Authentication endpoint:", planio_url)
	err = http.ListenAndServe(listen_address, nil)
	if err != nil {
		log.Panic(err)
	}
}
Example #30
0
// Proxy returns a handler to proxy HTTP(S) requests.
func Proxy(server *app.App, isHTTPS bool) func(w http.ResponseWriter, req *http.Request) {
	return func(w http.ResponseWriter, req *http.Request) {
		record, err := models.FindRecordByFQDN(server.DB, hostname(req.Host))
		if err != nil || record.ID == "" {
			server.Render.Data(w, http.StatusNotFound, nil)
			return
		}
		if record.Blacklist {
			server.Render.Data(w, http.StatusNotFound, nil)
			return
		}
		u, err := url.Parse(record.HandlerProtocol + "://" + record.HandlerHost + ":" + strconv.Itoa(record.HandlerPort))
		if err != nil {
			server.Render.Data(w, http.StatusNotFound, nil)
			return
		}
		proxy := httputil.NewSingleHostReverseProxy(u)
		if isHTTPS {
			proxy.Transport = &http.Transport{
				TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
			}
		}
		proxy.ServeHTTP(w, req)
	}
}