From c35da8f016c2baffa9fad1878e039f5b6de1ab9e Mon Sep 17 00:00:00 2001 From: simonpetit Date: Fri, 20 Dec 2024 14:43:49 +0000 Subject: [PATCH] init --- README.md | 0 go.mod | 5 +++++ go.sum | 2 ++ main.go | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 63 insertions(+) create mode 100644 README.md create mode 100644 go.mod create mode 100644 go.sum create mode 100644 main.go diff --git a/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..a598f8b --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module api_manager + +go 1.23.4 + +require github.com/go-chi/chi/v5 v5.2.0 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..7eba1a1 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/go-chi/chi/v5 v5.2.0 h1:Aj1EtB0qR2Rdo2dG4O94RIU35w2lvQSj6BRA4+qwFL0= +github.com/go-chi/chi/v5 v5.2.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= diff --git a/main.go b/main.go new file mode 100644 index 0000000..ad2f707 --- /dev/null +++ b/main.go @@ -0,0 +1,56 @@ +package main + +import ( + "log" + "net/http" + "net/http/httputil" + "net/url" + + "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.Get("/", func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("root.")) + }) + + log.Println("Proxy running on http://localhost:3333") + http.ListenAndServe(":3333", r) +} + +// reverseProxy forwards requests to the target URL with path rewriting +func reverseProxy(target *url.URL, targetPath string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Create a reverse proxy + proxy := httputil.NewSingleHostReverseProxy(target) + + // Update the request path to the target API path + r.URL.Path = targetPath + r.URL.Host = target.Host + r.URL.Scheme = target.Scheme + + // Set the Host header explicitly to match the target + r.Host = target.Host + + // Debug: Log the final URL being proxied + log.Printf("Proxying request to: %s%s", target, targetPath) + + // Serve the proxied request + proxy.ServeHTTP(w, r) + }) +}