57 lines
1.3 KiB
Go
57 lines
1.3 KiB
Go
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)
|
|
})
|
|
}
|