Last active
January 8, 2019 01:04
-
-
Save syntaqx/2b6658c09aa61a5ae4e4e3701d089bc9 to your computer and use it in GitHub Desktop.
Nav Interview PokeAPI Reverse Proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"net" | |
"net/http" | |
"net/http/httputil" | |
"net/url" | |
"os" | |
"strings" | |
"github.com/go-chi/chi" | |
"github.com/go-chi/chi/middleware" | |
) | |
func handleProxyRequest(w http.ResponseWriter, r *http.Request) { | |
// Include /api/v2/ in the path so I don't have to | |
u, err := url.Parse("https://pokeapi.co/api/v2/") | |
if err != nil { | |
http.Error(w, fmt.Sprintf("unable to create pokeapi url: %v", err), http.StatusBadGateway) | |
return | |
} | |
proxy := httputil.ReverseProxy{ | |
Director: func(r *http.Request) { | |
r.URL.Scheme = u.Scheme | |
r.URL.Host = u.Host | |
r.Host = u.Host | |
// pokeapi redirects non-trailing slashes, so this is required if we | |
// want to stay on proxy host. | |
r.URL.Path = u.Path + strings.TrimRight(r.URL.Path, "/") + "/" | |
r.Header.Set("X-Forwarded-Host", r.Header.Get("Host")) | |
}, | |
} | |
proxy.ServeHTTP(w, r) | |
} | |
func main() { | |
port, ok := os.LookupEnv("PORT") | |
if !ok { | |
port = "8080" | |
} | |
r := chi.NewMux() | |
r.Use(middleware.Logger) | |
r.Use(middleware.Recoverer) | |
r.Mount("/*", http.HandlerFunc(handleProxyRequest)) | |
httpServer := &http.Server{ | |
Addr: net.JoinHostPort("", port), | |
Handler: r, | |
} | |
log.Printf("http server listening at %s", httpServer.Addr) | |
if err := httpServer.ListenAndServe(); err != nil { | |
log.Panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment