api_manager/main.go
2025-01-06 17:00:50 +00:00

63 lines
1.6 KiB
Go

package main
import (
"log"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
func main() {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
// Parse the API URL
r.Handle("/cats/*", reverseProxy("https://catfact.ninja", "/cats"))
r.Handle("/coins/*", reverseProxy("https://api.coindesk.com/v1/bpi", "/coins"))
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 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(parsedURL)
// Rewrite the request path by stripping the prefix
originalPath := r.URL.Path
strippedPath := strings.TrimPrefix(originalPath, prefixToStrip)
log.Printf("stripped path %s", strippedPath)
// 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 proxied URL
log.Printf("Proxying request to: %s%s", parsedURL, strippedPath)
// Serve the proxied request
proxy.ServeHTTP(w, r)
})
}