Skip to content

Instantly share code, notes, and snippets.

@adamv
Created April 5, 2018 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamv/2dba29ee756c09b32cfa5e3478700b5f to your computer and use it in GitHub Desktop.
Save adamv/2dba29ee756c09b32cfa5e3478700b5f to your computer and use it in GitHub Desktop.
package main
import (
"net/http"
"fmt"
"io/ioutil"
"math/rand"
)
var letters = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
const HEADER_CORRELATION_ID = "correlationId"
type Frontend struct {
client *http.Client
}
func NewFrontend() *Frontend {
return &Frontend{client: &http.Client{}}
}
func (f *Frontend) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var correlationId = r.Header.Get(HEADER_CORRELATION_ID)
if correlationId == "" {
correlationId = newCorrelationId()
}
request, err := http.NewRequest("GET", "http://localhost:8082/url", nil)
request.Header.Set(HEADER_CORRELATION_ID, correlationId)
//resp, err := http.Get("http://localhost:8082/url")
resp, err := f.client.Do(request)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Fprint(w, "Hello (frontend)\n")
w.Write(body)
}
func randSeq(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func newCorrelationId() string {
return randSeq(16)
}
func backendHandler(w http.ResponseWriter, r *http.Request) {
var correlationId = r.Header.Get(HEADER_CORRELATION_ID)
fmt.Fprint(w, "Hello (backend)\n")
fmt.Fprintf(w, "Correlation ID: %s\n", correlationId)
}
func main() {
// backend service
var backendService *http.ServeMux = http.NewServeMux()
backendService .HandleFunc("/", backendHandler)
go http.ListenAndServe(":8082", backendService)
// frontend service
var frontendService = http.NewServeMux()
frontendService.Handle("/", NewFrontend())
http.ListenAndServe(":8081", frontendService)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment