This commit is contained in:
simonpetit 2024-12-20 14:43:49 +00:00
commit c35da8f016
4 changed files with 63 additions and 0 deletions

0
README.md Normal file
View File

5
go.mod Normal file
View File

@ -0,0 +1,5 @@
module api_manager
go 1.23.4
require github.com/go-chi/chi/v5 v5.2.0 // indirect

2
go.sum Normal file
View File

@ -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=

56
main.go Normal file
View File

@ -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)
})
}