func handler(proxy *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
	return func(writer http.ResponseWriter, request *http.Request) {
		vars := mux.Vars(request)
		log.Println(vars["branch"])
		proxy.ServeHTTP(writer, request)
	}
}
// This function isn't the default handler but returns the default handler, i.e. has
// a function closure. This allows me to set up my Mutex secured increment and decrement functions
// and assemble an access queue so that only five of the concurrent requests are being processed
// at any time, and put the function that reports the number of requests in a a global,
// so it may be called from main().
func makeDefaultHandler(p *httputil.ReverseProxy, overcapacityBehavior string) func(http.ResponseWriter, *http.Request) {
	capacityQueue := make(chan int, maxConcurrentRequests) // the Brass Rings, as it were.
	for i := 0; i < maxConcurrentRequests; i++ {           // grab one, and you're in. :)
		capacityQueue <- i
	}

	incrementConcurrentReqs, decrementConcurrentReqs, tellMeNumReqs := makeTotalConcurrentCounters()
	totalReqs = tellMeNumReqs

	return func(w http.ResponseWriter, r *http.Request) {
		incrementConcurrentReqs() // do this BEFORE pulling off queue; we want to count the reqs that wait
		log.Printf("New Request: now concurrent requests: %03d\n", tellMeNumReqs())
		if overcapacityBehavior == rejectOvercapacityReqs { // Reject more than five concurrent requests
			if tellMeNumReqs() > maxReqsAllowed {
				log.Printf("Surpassed capacity for %03d concurrent requests: sending back 503 error\n", maxReqsAllowed)
				http.Error(w, "Maximum Capacity Exceeded", http.StatusServiceUnavailable)
				return
			}
		} // overcapacityBehavior == rejectOvercapacityReqs
		queueSlot := <-capacityQueue
		log.Printf("queueSlot %d, Client requested %s, forwarding to localhost:8181 (totalReqs = %d)\n",
			queueSlot, r.URL, tellMeNumReqs())
		p.ServeHTTP(w, r)
		capacityQueue <- queueSlot
		decrementConcurrentReqs()
		log.Printf("Request completed: now concurrent requests: %03d\n", tellMeNumReqs())
	}
}
func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		if isLogging {
			log.Printf("- %v, %v, %v", r.RemoteAddr, r.Method, r.RequestURI)
		}
		p.ServeHTTP(w, r)
	}
}
Exemple #4
0
// ProxyHandle registers a new resource with its handler
func (r *AppRoute) ProxyHandle(method string, path string, proxy *httputil.ReverseProxy, filters ...ResponseFilter) {
	r.Handle(method, path, func(ctx *Context) {
		for _, filter := range filters {
			ctx.Response.Before(filter)
		}

		proxy.ServeHTTP(ctx.Response, ctx.Request)
	})
}
Exemple #5
0
// Proxy will setup a direct proxy inbetween this service and the destination
// service.
func (c *Context) Proxy(targetURL string, rewrite func(req *http.Request)) error {
	target, err := url.Parse(targetURL)
	if err != nil {
		return err
	}

	// Define our custom request director to ensure that the correct headers are
	// forwarded as well as having the request path and query rewritten
	// properly.
	director := func(req *http.Request) {
		req.URL.Scheme = target.Scheme
		req.URL.Host = target.Host
		req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)

		if target.RawQuery == "" || req.URL.RawQuery == "" {
			req.URL.RawQuery = target.RawQuery + req.URL.RawQuery
		} else {
			req.URL.RawQuery = target.RawQuery + "&" + req.URL.RawQuery
		}

		// Set the headers on the incoming request by clearing them all out.
		req.Header = make(http.Header)

		// Rewrite the request for the director if a rewrite function was passed.
		if rewrite != nil {
			rewrite(req)
		}
	}

	// Make a copy of the current upstream headers on the request.
	upstreamHeaders := make(http.Header)
	copyHeader(upstreamHeaders, c.Header())

	// Create a new reverse proxy. We need to to this here because for the path
	// rewriting we may need access to variables stored in this specific
	// request's path parameters which can allow to be overridden via the
	// rewrite argument to this function.
	proxy := httputil.ReverseProxy{Director: director}

	// Create a new proxy response writer that will record the http status code
	// issued by the reverse proxy.
	prw := ProxyResponseWriter{
		UpstreamHeaders: upstreamHeaders,
		ResponseWriter:  c.ResponseWriter,
	}

	// Serve the request via the built in handler here.
	proxy.ServeHTTP(&prw, c.Request)

	// Set the status code so that we can log the response code later.
	c.Status = prw.Status

	return nil
}
Exemple #6
0
func handler(p *httputil.ReverseProxy, redisClient *redis.Client) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {

		hash := hashKey(r)

		serializableResponse := SerializableResponse{make(map[string][]string), nil}

		s, err := redisClient.Get(hash)
		if err != nil { // The request is not cached
			rec := httptest.NewRecorder()
			log.Println("Non cached: " + hash)

			// Perform the real request and cache it
			p.ServeHTTP(rec, r)

			for k, v := range rec.Header() {
				serializableResponse.Header[k] = v
			}
			serializableResponse.Body = rec.Body.Bytes()

			jsonResponse, err := json.Marshal(serializableResponse)
			if err != nil {
				panic(err)
			}
			redisClient.Set(hash, jsonResponse)
			w.Header().Set("X-Eidetic", "Live request")

		} else { // The request is cached
			log.Println("Cached!: " + hash)

			// Load the cached request
			err = json.Unmarshal([]byte(s), &serializableResponse)
			if err != nil {
				panic(err)
			}

			w.Header().Set("X-Eidetic", "Cached request")

		}

		//Copy the data to the actual ResponseWriter
		// log.Println("\n\n\nResponse Headers:")
		for k, v := range serializableResponse.Header {
			w.Header()[k] = v
			// log.Println(k + ": ")
			// for _, str := range v {
			// 	log.Println("  " + str)
			// }
		}
		w.Write([]byte(serializableResponse.Body))
		// log.Println("\nResponse body:\n" + string(serializableResponse.Body))

	}
}
Exemple #7
0
func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {

	return func(w http.ResponseWriter, r *http.Request) {
		log.Println(r.URL.Path)

		return
		_, err := os.Stat(CACHE_PATH + r.URL.Path)
		if os.IsNotExist(err) {
			log.Println("Miss")
		} else {
			p.ServeHTTP(w, r)
		}

	}
}
Exemple #8
0
func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		r.Header.Set("X-Forwarded-Proto", "https")

		session, _ := sessions.SessionStore.Get(r, "session-name")
		userLoginId := session.Values[sessions.USER_LOGIN_ID]
		if userLoginId != nil {
			r.Header.Set("REMOTE_USER", userLoginId.(string))
		}
		p.ServeHTTP(w, r)

		newLoc := w.Header().Get("Location")
		if newLoc != "" {
			log.Println("Redirecting.. " + newLoc)
		}
	}
}
Exemple #9
0
func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if strings.HasSuffix(r.Host, "manveru.name") {
			proxy := httputil.ReverseProxy{Director: manveruDotName}
			proxy.ServeHTTP(w, r)
		} else if strings.HasSuffix(r.Host, "nsans.eu") {
			proxy := httputil.ReverseProxy{Director: nsansDotEu}
			proxy.ServeHTTP(w, r)
		} else {
			w.WriteHeader(404)
		}
	})

	err := http.ListenAndServe("0.0.0.0:80", nil)
	if err != nil {
		log.Fatalln("ListenAndServe:", err)
	}
}
func handler(fw *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
	return func(wr http.ResponseWriter, req *http.Request) {
		wr.Header()["X-Powered-By"] = []string{"jenkins-authentication-proxy/" + version}
		if isOpenPrefix(req.RequestURI) {
			fw.ServeHTTP(wr, req)
			return
		}

		if authed, err := authenticateWithBackend(req); err != nil {
			wr.WriteHeader(http.StatusInternalServerError)
			fmt.Fprint(wr, "error", err)
			log.Print(err)
		} else if authed {
			fw.ServeHTTP(wr, req)
		} else {
			wr.Header()["Www-Authenticate"] = []string{"Basic realm=\"Jenkins\""}
			wr.WriteHeader(http.StatusUnauthorized)
		}
	}
}
Exemple #11
0
func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		log.Println(r.URL)
		p.ServeHTTP(w, r)
	}
}
Exemple #12
0
func proxyDebugHandler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		log.Println("proxy serving request for: ", r.URL)
		p.ServeHTTP(w, r)
	}
}
func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		log.Printf("%s %s %s", r.RemoteAddr, r.Method, r.URL)
		p.ServeHTTP(w, r)
	}
}
Exemple #14
0
func proxyHandler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		r.Header.Add("Proxy-RemoteIP", strings.Split(r.RemoteAddr, ":")[0])
		p.ServeHTTP(w, r)
	}
}