// Minimal jim-bot web interface wrapper which generates 10 random // corporate gibberish sentences on page load. package main import ( "encoding/json" "log" "net/http" "strings" "pablotron.org/jim-bot/bot" ) // Send response as JSON-encoded array. func doHomeJson(w http.ResponseWriter) { // generate sentences sentences := bot.N(10) // write response header and body w.Header().Add("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(sentences); err != nil { log.Print(err) } } // Send response as newline-delimited text. func doHomeText(w http.ResponseWriter) { // generate response body body := []byte(strings.Join(bot.N(10), "\n") + "\n") // write response header and body w.Header().Add("Content-Type", "text/plain") if _, err := w.Write(body); err != nil { log.Print(err) } } // Home page handler. // // By default this handler responds with a newline-delimited list of // sentences. However if both of the following conditions are true, // then the response is a JSON-encoded array of sentences: // // - The request method is POST // - The request Accept header is "application/json" func doHome(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodPost && r.Header.Get("Accept") == "application/json" { doHomeJson(w) // send json } else { doHomeText(w) // send text } } func main() { http.HandleFunc("/", doHome) http.ListenAndServe(":8080", nil) }