Skip to content

Instantly share code, notes, and snippets.

@habibiefaried
Created June 16, 2024 09:26
Show Gist options
  • Save habibiefaried/fbfb894928dd24c48dc2cdd0ad8187d7 to your computer and use it in GitHub Desktop.
Save habibiefaried/fbfb894928dd24c48dc2cdd0ad8187d7 to your computer and use it in GitHub Desktop.
Basic reverse proxy golang
package main
import (
"io"
"log"
"net/http"
)
func handleProxy(w http.ResponseWriter, r *http.Request) {
// Define the target server
target := "http://example.com"
// Create the request to the target server
req, err := http.NewRequest(r.Method, target+r.RequestURI, r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Copy headers from the original request
for k, v := range r.Header {
req.Header[k] = v
}
// Send the request to the target server
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
// Copy headers and status code from the target server response
for k, v := range resp.Header {
w.Header()[k] = v
}
w.WriteHeader(resp.StatusCode)
// Copy the response body from the target server
_, err = io.Copy(w, resp.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func main() {
http.HandleFunc("/", handleProxy)
log.Println("Starting proxy server on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment