Created
February 10, 2021 08:53
-
-
Save egeneralov/0f5cd2ebe6543bcbf5c09ec50b3c8da8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"fmt" | |
"encoding/json" | |
"github.com/valyala/fasthttp" | |
) | |
var ( | |
proxyClient = &fasthttp.HostClient{ | |
Addr: "cdimage.debian.org:80", | |
} | |
storage = make(map[string]*fasthttp.Response) | |
) | |
func ReverseProxyHandler(ctx *fasthttp.RequestCtx) { | |
req := &ctx.Request | |
resp := &ctx.Response | |
path := string(ctx.Request.URI().Path()) | |
if path == "/stats" { | |
storageDump := make(map[string]int) | |
for k, v := range storage { | |
storageDump[k] = len(v.Body()) | |
} | |
j, je := json.Marshal(storageDump) | |
if je == nil { | |
fmt.Fprintf(ctx, string(j)) | |
} | |
return | |
} | |
_, exist := storage[path] | |
if !exist { | |
ctx.Logger().Printf("request") | |
if err := proxyClient.Do(req, resp); err != nil { | |
ctx.Logger().Printf("error when proxying the request: %s", err) | |
} | |
storage[path] = &fasthttp.Response{} | |
resp.CopyTo(storage[path]) | |
} | |
storage[path].CopyTo(resp) | |
} | |
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