From e10bafbf7639042a946c73a309d1b47b2f466333 Mon Sep 17 00:00:00 2001 From: simonpetit Date: Fri, 20 Dec 2024 17:06:42 +0000 Subject: [PATCH] refining --- main.go | 38 ++++++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/main.go b/main.go index ad2f707..bf337e7 100644 --- a/main.go +++ b/main.go @@ -5,25 +5,23 @@ import ( "net/http" "net/http/httputil" "net/url" + "strings" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" ) func main() { - apiURL := "https://catfact.ninja" r := chi.NewRouter() r.Use(middleware.Logger) r.Use(middleware.Recoverer) // Parse the API URL - parsedURL, err := url.Parse(apiURL) - if err != nil { - log.Fatalf("Failed to parse API URL: %v", err) - } - r.Handle("/cats", reverseProxy(parsedURL, "/fact")) + r.Handle("/cats/*", reverseProxy("https://catfact.ninja")) + + r.Handle("/coins/*", reverseProxy("https://api.coindesk.com/v1/bpi")) r.Get("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("root.")) @@ -34,21 +32,29 @@ func main() { } // reverseProxy forwards requests to the target URL with path rewriting -func reverseProxy(target *url.URL, targetPath string) http.Handler { +func reverseProxy(target string, prefixToStrip string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Parse the target URL + parsedURL, err := url.Parse(target) + if err != nil { + log.Fatalf("Failed to parse target URL: %v", err) + } + // Create a reverse proxy - proxy := httputil.NewSingleHostReverseProxy(target) + proxy := httputil.NewSingleHostReverseProxy(parsedURL) - // Update the request path to the target API path - r.URL.Path = targetPath - r.URL.Host = target.Host - r.URL.Scheme = target.Scheme + // Rewrite the request path by stripping the prefix + originalPath := r.URL.Path + strippedPath := strings.TrimPrefix(originalPath, prefixToStrip) - // Set the Host header explicitly to match the target - r.Host = target.Host + // Update the proxied request URL + r.URL.Path = strippedPath // Use the stripped path in the proxy + r.URL.Scheme = parsedURL.Scheme + r.URL.Host = parsedURL.Host + r.Host = parsedURL.Host - // Debug: Log the final URL being proxied - log.Printf("Proxying request to: %s%s", target, targetPath) + // Debug: Log the final proxied URL + log.Printf("Proxying request to: %s%s", parsedURL, strippedPath) // Serve the proxied request proxy.ServeHTTP(w, r)