Skip to content

Instantly share code, notes, and snippets.

@ray1729
Created April 19, 2017 08:30
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 ray1729/0449ee1964b23432eb2ae1e8299db73b to your computer and use it in GitHub Desktop.
Save ray1729/0449ee1964b23432eb2ae1e8299db73b to your computer and use it in GitHub Desktop.
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