cached proxied resources

This commit is contained in:
blek 2023-11-05 15:05:30 +10:00
parent 3f859dac77
commit 280f1a038b
Signed by: blek
GPG Key ID: 14546221E3595D0C
1 changed files with 24 additions and 9 deletions

View File

@ -45,6 +45,25 @@ func (self Config) Validate() int {
return 0 return 0
} }
func (self Resource) GetProxied() ([]byte, error) {
cached, exists := ProxyResourceCache[self.Url];
if exists {
return cached, nil
}
resp, err := http.Get(self.Url)
if err != nil { return make([]byte, 0, 0), err }
buf, err := ioutil.ReadAll(resp.Body)
if err != nil { return make([]byte, 0, 0), err }
ProxyResourceCache[self.Url] = buf
return buf, nil
}
var ProxyResourceCache map[string][]byte = make(map[string][]byte)
func main() { func main() {
var conf Config var conf Config
@ -82,19 +101,15 @@ func main() {
if ! strings.HasPrefix(res.Url, "file://") { if ! strings.HasPrefix(res.Url, "file://") {
if res.Proxied { if res.Proxied {
resp, err := http.Get(res.Url) data, err := res.GetProxied()
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
// we failed, send a redirect instead
// (next executed line would be 115)
} else { } else {
c.Response().Header.SetContentType(res.Mime) c.Response().Header.SetContentType(res.Mime)
// c.Response().Header.SetContentLength(resp.ContentLength) c.Response().Header.SetContentLength(len(data))
buf, err := ioutil.ReadAll(resp.Body) return c.Send(data)
if err != nil {
log.Fatalln(err)
return c.Status(500).SendString("Internal error")
}
return c.Send(buf)
} }
} }