Skip to content

Instantly share code, notes, and snippets.

@klrkdekira
Created August 22, 2016 08:38
Show Gist options
  • Save klrkdekira/71e2852d3ae5791dc471ec3f5f3b4f73 to your computer and use it in GitHub Desktop.
Save klrkdekira/71e2852d3ae5791dc471ec3f5f3b4f73 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"sync"
)
type RobinHood struct {
// poor man's counter
counter int
mu *sync.Mutex
One, Two, Three func(http.ResponseWriter, *http.Request)
}
func (rh *RobinHood) ServeHTTP(w http.ResponseWriter, r *http.Request) {
rh.mu.Lock()
defer rh.mu.Unlock()
if rh.counter == 0 {
rh.One(w, r)
} else if rh.counter == 1 {
rh.Two(w, r)
} else if rh.counter == 2 {
rh.Three(w, r)
}
rh.counter = (rh.counter + 1) % 3
}
func makeRobinHood() *RobinHood {
return &RobinHood{
counter: 0,
mu: &sync.Mutex{},
One: makeHandler("one"),
Two: makeHandler("two"),
Three: makeHandler("three"),
}
}
func makeHandler(msg string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, from %s!", msg)
}
}
func main() {
server := &http.Server{
Handler: makeRobinHood(),
Addr: ":9090",
}
// Starts webserver in background
go func() {
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
}()
fmt.Println("Started web server")
// Our request
req, err := http.NewRequest("GET", "http://127.0.0.1:9090/", nil)
if err != nil {
log.Fatal(err)
}
req.Close = true
fmt.Println("Calling one")
lookup(req)
fmt.Println("Calling two")
lookup(req)
fmt.Println("Calling three")
lookup(req)
fmt.Println("Calling one again")
lookup(req)
fmt.Println("You see, I'm an oracle")
fmt.Println("All done! Exited")
}
func lookup(req *http.Request) {
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Received response, %s\n", b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment