本文整理汇总了Golang中net/http/httputil.ReverseProxy类的典型用法代码示例。如果您正苦于以下问题:Golang ReverseProxy类的具体用法?Golang ReverseProxy怎么用?Golang ReverseProxy使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ReverseProxy类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: handler
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)
}
}
示例2: makeDefaultHandler
// 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())
}
}
示例3: main
func main() {
// get /blog => to server1
// get /login => to server2
var target1, target2 *url.URL
var err error
if target1, err = url.Parse(SERVER1); err != nil {
log.Fatal("parse url: ", err)
}
if target2, err = url.Parse(SERVER2); err != nil {
log.Fatal("parse url: ", err)
}
reverseProxy := new(httputil.ReverseProxy)
reverseProxy.Director = func(req *http.Request) {
req.URL.Scheme = "http"
if strings.HasPrefix(req.URL.Path, "/blog") {
req.URL.Host = target1.Host
}
if strings.HasPrefix(req.URL.Path, "/login") {
req.URL.Host = target2.Host
}
}
err = http.ListenAndServe(":80", reverseProxy)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
示例4: handler
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)
}
}
示例5: ProxyHandle
// 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)
})
}
示例6: Proxy
// 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
}
示例7: handler
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))
}
}
示例8: handler
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)
}
}
}
示例9: handler
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)
}
}
}
示例10: setProxyDirector
func setProxyDirector(proxy *httputil.ReverseProxy) {
director := proxy.Director
proxy.Director = func(req *http.Request) {
director(req)
// use RequestURI so that we aren't unescaping encoded slashes in the request path
req.URL.Opaque = req.RequestURI
req.URL.RawQuery = ""
}
}
示例11: setProxyUpstreamHostHeader
func setProxyUpstreamHostHeader(proxy *httputil.ReverseProxy, target *url.URL) {
director := proxy.Director
proxy.Director = func(req *http.Request) {
director(req)
// use RequestURI so that we aren't unescaping encoded slashes in the request path
req.Host = target.Host
req.URL.Opaque = req.RequestURI
req.URL.RawQuery = ""
}
}
示例12: handler
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)
}
}
}
示例13: main
func main() {
var srv httputil.ReverseProxy
log.SetFlags(0)
flag.Parse()
if *file == "" {
log.Print("config file (-c) is required")
flag.PrintDefaults()
os.Exit(1)
}
if cfg, err := config.ParseFile(*file); err != nil {
log.Fatalf("parse %s failed: %s", *file, err)
} else {
srv.Director = cfg.MapRequest
if *addr == "" {
*addr = cfg.Address
}
}
http.Handle("/render", accesslog.Handler(&srv, nil))
log.Fatal(http.ListenAndServe(*addr, nil))
}
示例14: main
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)
}
}
示例15: proxyHandler
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)
}
}