Created
August 6, 2019 03:45
-
-
Save sidneyw/d22cd037ed8387531feff45fcdc8b6a7 to your computer and use it in GitHub Desktop.
This file contains 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 ( | |
"bytes" | |
"encoding/json" | |
"flag" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"net/http/httputil" | |
"net/url" | |
"strconv" | |
) | |
func parseResponse(res *http.Response, unmarshalStruct interface{}) error { | |
body, err := ioutil.ReadAll(res.Body) | |
if err != nil { | |
return err | |
} | |
res.Body.Close() | |
res.Body = ioutil.NopCloser(bytes.NewBuffer(body)) | |
return json.Unmarshal(body, unmarshalStruct) | |
} | |
func captureMetrics(m map[string]interface{}) error { | |
// Add your metrics capture code here | |
log.Printf("captureMetrics = %+v\n", m) | |
return nil | |
} | |
func main() { | |
port := flag.Int("port", 8080, "port to listen on") | |
targetURL := flag.String("target-url", "", "downstream service url to proxy to") | |
flag.Parse() | |
u, err := url.Parse(*targetURL) | |
if err != nil { | |
log.Fatalf("Could not parse downstream url: %s", *targetURL) | |
} | |
proxy := httputil.NewSingleHostReverseProxy(u) | |
director := proxy.Director | |
proxy.Director = func(req *http.Request) { | |
director(req) | |
req.Header.Set("X-Forwarded-Host", req.Header.Get("Host")) | |
req.Host = req.URL.Host | |
} | |
proxy.ModifyResponse = func(res *http.Response) error { | |
responseContent := map[string]interface{}{} | |
err := parseResponse(res, &responseContent) | |
if err != nil { | |
return err | |
} | |
return captureMetrics(responseContent) | |
} | |
http.HandleFunc("/", proxy.ServeHTTP) | |
log.Printf("Listening on port %d", *port) | |
log.Fatal(http.ListenAndServe(":"+strconv.Itoa(*port), nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment