Senior
What is a reverse proxy and what is typically used?
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. It acts as an intermediary between the client and the server, hiding the internal network structure and providing additional functions.
Main tasks of a reverse proxy:
- Load balancing between multiple servers.
- Caching responses to speed up processing.
- SSL termination (handling HTTPS).
- Protecting internal servers from direct access.
- Compression and traffic optimization.
Common solutions for reverse proxy:
- Nginx — a popular web server and reverse proxy with extensive capabilities.
- HAProxy — a high-performance load balancer and reverse proxy.
- Traefik — a modern dynamic reverse proxy, often used in container environments.
In Go, you can use the net/http/httputil package to create your own reverse proxy. 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))
}
This code redirects all requests from port 9090 to the local server on port 8080.