diff options
-rw-r--r-- | main.go | 33 |
1 files changed, 31 insertions, 2 deletions
@@ -3,6 +3,7 @@ package main import ( + "encoding/json" "log" "net/http" "strings" @@ -10,8 +11,20 @@ import ( "pablotron.org/jim-bot/bot" ) -// serve home page -func doHome(w http.ResponseWriter, _ *http.Request) { +// 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") @@ -22,6 +35,22 @@ func doHome(w http.ResponseWriter, _ *http.Request) { } } +// 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) |