hookenz
hookenz

Reputation: 38907

What's required to build a complete HTTP reverse proxy in go?

A naive reverse proxy is like this:

package main

import (
    "net/http"
    "net/http/httputil"
    "net/url"
    "fmt"
)

func main() { 
    // New functionality written in Go
    http.HandleFunc("/new", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "New function")
    })

    // Anything we don't do in Go, we pass to the old platform
    u, _ := url.Parse("http://www.google.com/")
    http.Handle("/", httputil.NewSingleHostReverseProxy(u))

    // Start the server
    http.ListenAndServe(":8080", nil)
}

But, this is incomplete. Depending on the website you might not get anything useful back. Some do https redirect. Some complain about direct ip access. I suspect virtual hosts don't work? not sure.

What does a true reverse proxy do that makes it complete?

Upvotes: 1

Views: 1251

Answers (1)

Jonathan Hall
Jonathan Hall

Reputation: 79614

The simplest way to implement a reverse HTTP proxy in Go is with the httputil.ReverseProxy type in the standard library.

This gives you the flexibility to set a Director function which can modify the incoming requests, and a Transport to possibly modify requests and/or responses on-the-fly.

It should be able to handle the vast majority of reverse proxy situations. I use it with great success in a project of mine.

Upvotes: 3

Related Questions