GoChain/proxy.go

84 lines
2.1 KiB
Go

package main
import (
"io"
"log"
"net/http"
"strings"
"github.com/labstack/echo/v4"
)
// thx a lot to Mellifluery for that code
// ^^
func Proxy(ctx echo.Context) error {
// may be used to provide specialized configurations
// originalServiceUrl := ctx.Param("originalServiceUrl")
url := ctx.Param("url")
if url == "" {
return ctx.NoContent(http.StatusNoContent)
}
if !strings.HasPrefix(url, "http") {
url = "https://" + url
}
log.Println("Got request: " + strings.ToUpper(ctx.Request().Method) + " " + url)
req, err := http.NewRequest(ctx.Request().Method, url, ctx.Request().Body)
if err != nil {
log.Println("Error in NewRequest: " + err.Error())
return ctx.String(500, err.Error())
}
for s := range ctx.Request().Header {
if s == "Origin" || s == "Referer" {
continue
}
println("Added header: " + s + ": " + ctx.Request().Header.Get(s))
req.Header.Set(s, ctx.Request().Header.Get(s))
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Println("Error in DefaultClient.Do: " + err.Error())
return ctx.String(500, err.Error())
}
defer resp.Body.Close()
for s := range resp.Header {
if strings.HasPrefix(strings.ToLower(s), "access-control-allow") {
ctx.Response().Header().Set(s, "*")
} else {
ctx.Response().Header().Set(s, resp.Header.Get(s))
}
}
data, err := io.ReadAll(resp.Body)
if err != nil {
log.Println("Error in ReadAll: " + err.Error())
return err
}
contentTypeRaw := resp.Header.Get("Content-Type")
//contentType := strings.Split(contentTypeRaw, "/")
response := string(data)
log.Println("Content: " + response)
if ctx.Request().Method == "OPTIONS" {
ctx.Response().Header().Set("Access-Control-Allow-Headers", "origin, content-type, accept")
} else {
ctx.Response().Header().Set("Access-Control-Allow-Headers", "*")
}
ctx.Response().Header().Set("Access-Control-Allow-Origin", ctx.Request().Header.Get("Origin"))
ctx.Response().Header().Set("Access-Control-Allow-Methods", "*")
ctx.Response().Header().Set("Access-Control-Allow-Credentials", "true")
ctx.Response().Header().Set("Allow", "*")
return ctx.Blob(200, contentTypeRaw, data)
}