This commit is contained in:
simonpetit 2024-12-20 17:06:42 +00:00
parent c35da8f016
commit e10bafbf76

38
main.go
View File

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