Fragment Description:



* Use of 'net/http/httputil.ReverseProxy'.
A simple web proxy used to provide unauthenticated access to a web service that required HTTP basic auth.
The httputil package and the ReverseProxy struct.

httputilReverseProxy

Last update, on 2015, Fri 9 Oct, 16:15:40

/* ... <== see fragment description ... */

package main

import (
    "flag"
    "log"
    "net/http"
    "net/http/httputil"
    "net/url"
)

var target = flag.String("target", "http://www.google.com/", "Where to go.")
var addr = flag.String("listen", ":12345", "Address/port on which to listen.")
var auth = flag.String("auth", "", "Authorization header to add (optional).")

func main() {
    flag.Parse()
    targetUrl, err := url.Parse(*target)
    if err != nil {
        log.Fatalf("Error parsing target ``%s'': ", target, err)
    }
    /* sign: type ReverseProxy struct {
               // Director must be a function which modifies
               // the request into a new request to be sent
               // using Transport. Its response is then copied
               // back to the original client unmodified.
               Director func(*http.Request)
               // The transport used to perform proxy requests.
               // If nil, http.DefaultTransport is used.
               Transport http.RoundTripper
               // FlushInterval specifies the flush interval
               // to flush to the client while copying the
               // response body.
               // If zero, no periodic flushing is done.
               FlushInterval time.Duration
               // ErrorLog specifies an optional logger for errors
               // that occur when attempting to proxy the request.
               // If nil, logging goes to os.Stderr via the log package's
               // standard logger.
               ErrorLog *log.Logger
           }
   */
    // ReverseProxy is an HTTP Handler that takes an incoming request
    // and sends it to another server, proxying the response back to the client.
    proxy := httputil.ReverseProxy{
        Director: func(req *http.Request) {
            req.URL.Scheme = targetUrl.Scheme
            req.URL.Host = targetUrl.Host
            req.Host = targetUrl.Host
            if *auth != "" {
                req.Header.Set("Authorization", *auth)
            }
        },
    }
    // note the handler passed to ListenAndServe.
    log.Fatal(http.ListenAndServe(*addr, &proxy))
}

/*
ReverseProxy is an HTTP Handler that takes an incoming request
and sends it to another server, proxying the response back to the client.
*/



Comments