Here is a very basic reverse proxy in Golang using the net/http
library. To create a reverse proxy, we need to instantiate an instance of the http.ReverseProxy object.
Before that, you should obtain an SSL certificate for your domain. You can get a free SSL certificate from providers like Let’s Encrypt.
Once you’ve done that, let’s get started.
Step 1: Create an origin server.
This will be a primary HTTP server that listens on port 8080:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "This is the origin server")
})
http.ListenAndServe(":8080", nil)
}
Step 2: Create a reverse proxy.
This will be another server that listens on port 8443 and forwards all requests to the origin server:
package main
import (
"crypto/tls"
"log"
"net/http"
"net/http/httputil"
"net/url"
)
func main() {
target, _ := url.Parse("http://localhost:8080")
proxy := httputil.NewSingleHostReverseProxy(target)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
proxy.ServeHTTP(w, r)
})
// SSL config
sslConfig := &tls.Config{
MinVersion: tls.VersionTLS13,
PreferServerCipherSuites: true,
}
server := &http.Server{
Addr: ":8443",
Handler: http.DefaultServeMux,
TLSConfig: sslConfig,
}
log.Fatal(server.ListenAndServeTLS("path-to-your-server.crt", "path-to-your-server.key"))
}
In the code above, replace “path-to-your-server.crt” and “path-to-your-server.key” with the path to your certificate and private key files, respectively.
This will listen on port 8443 and forward all traffic to the origin server listening on port 8080. Note that the reverse proxy is using TLS, so it’s secured.
Steps 3 and 4: Forward a client request to the origin server and copy the origin server response to the client.
These steps are taken care of by the proxy.ServeHTTP(w, r) call in our reverse proxy server. The http.ReverseProxy object automatically forwards the client request to the target server and copies the response from the target server back to the client.
Again, in the real world, you would want to add error handling, logging, and possibly other features like load balancing. But this should give you a good idea of how to start.
Remember to run your origin server before running your reverse proxy server.