Skip to content

Instantly share code, notes, and snippets.

@night-codes
Created April 18, 2021 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save night-codes/e5789a5eff63551dcc91b30f074651c4 to your computer and use it in GitHub Desktop.
Save night-codes/e5789a5eff63551dcc91b30f074651c4 to your computer and use it in GitHub Desktop.
fasthttp reverse proxy
import (
"github.com/valyala/fasthttp"
)
var proxyClient = &fasthttp.HostClient{
Addr: "upstream.host:port",
// set other options here if required - most notably timeouts.
}
func ReverseProxyHandler(ctx *fasthttp.RequestCtx) {
req := &ctx.Request
resp := &ctx.Response
prepareRequest(req)
if err := proxyClient.Do(req, resp); err != nil {
ctx.Logger().Printf("error when proxying the request: %s", err)
}
postprocessResponse(resp)
}
func prepareRequest(req *fasthttp.Request) {
// do not proxy "Connection" header.
req.Header.Del("Connection")
// strip other unneeded headers.
// alter other request params before sending them to upstream host
}
func postprocessResponse(resp *fasthttp.Response) {
// do not proxy "Connection" header
resp.Header.Del("Connection")
// strip other unneeded headers
// alter other response data if needed
}
func main() {
if err := fasthttp.ListenAndServe(":8080", reverseProxyHandler); err != nil {
log.Fatalf("error in fasthttp server: %s", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment