Sobes.tech
Middle

What is a reverse proxy and how can it be implemented?

sobes.tech AI

Answer from AI

A reverse proxy is a server that accepts requests from clients and forwards them to one or more internal servers, hiding them from the client. It can perform load balancing, caching, SSL termination, and provide an additional layer of security.

In Go, a reverse proxy can be implemented using the net/http/httputil package, which contains the ReverseProxy type.

Example of a simple reverse proxy in Go:

package main

import (
    "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)
    })

    log.Println("Starting reverse proxy on :9090")
    log.Fatal(http.ListenAndServe(":9090", nil))
}

In this example, all requests to port 9090 will be forwarded to the local server on port 8080.