Skip to content

Instantly share code, notes, and snippets.

@ray1729
Created Apr 19, 2017
Embed
What would you like to do?
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
)
func main() {
http.HandleFunc("/", dominoHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func dominoHandler(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
log.Printf("Received request: %v\n", query)
a := query["a"]
if a == nil || len(a[0]) == 0 {
log.Println("No a=... in query, returning random word")
fmt.Fprintf(w, "pseudorandom")
return
}
addrs := strings.Split(a[0], ",")
next_hop := fmt.Sprintf("http://192.168.21.%s:9001/?a=%s", addrs[0], strings.Join(addrs[1:], ","))
resp, err := http.Get(next_hop)
if err != nil {
log.Printf("Error retrieving %s: %v", next_hop, err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Error retrieving %s\n", next_hop)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("Error reading response body: %v", err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Failed to read response body from %s", next_hop)
return
}
if len(body) == 0 {
fmt.Fprintf(w, "random")
} else {
fmt.Fprintf(w, "%s,random", body)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment