- commit
- 910a7a5
- parent
- ae3f389
- author
- Eric Bower
- date
- 2024-10-14 02:28:12 +0000 UTC
refactor(pgs): use httputil rev proxy to external service
1 files changed,
+11,
-14
+11,
-14
1@@ -13,6 +13,7 @@ import (
2 "strings"
3 "time"
4
5+ "net/http/httputil"
6 _ "net/http/pprof"
7
8 "github.com/gorilla/feeds"
9@@ -229,24 +230,20 @@ func (h *AssetHandler) handle(logger *slog.Logger, w http.ResponseWriter, r *htt
10 "destination", fp.Filepath,
11 "status", fp.Status,
12 )
13- // fetch content from url and serve it
14- resp, err := http.Get(fp.Filepath)
15+
16+ destUrl, err := url.Parse(fp.Filepath)
17 if err != nil {
18- logger.Error(
19- "external service not found",
20- "err", err,
21- "status", http.StatusNotFound,
22- )
23- http.Error(w, "404 not found", http.StatusNotFound)
24+ http.Error(w, err.Error(), http.StatusInternalServerError)
25 return
26 }
27-
28- w.Header().Set("content-type", resp.Header.Get("content-type"))
29- w.WriteHeader(status)
30- _, err = io.Copy(w, resp.Body)
31- if err != nil {
32- logger.Error("io copy", "err", err.Error())
33+ proxy := httputil.NewSingleHostReverseProxy(destUrl)
34+ oldDirector := proxy.Director
35+ proxy.Director = func(r *http.Request) {
36+ oldDirector(r)
37+ r.Host = destUrl.Host
38+ r.URL = destUrl
39 }
40+ proxy.ServeHTTP(w, r)
41 return
42 }
43