diff options
author | Paul Duncan <pabs@pablotron.org> | 2025-03-08 00:37:24 -0500 |
---|---|---|
committer | Paul Duncan <pabs@pablotron.org> | 2025-03-08 00:37:24 -0500 |
commit | 1bad38cc81f75c90f7192989207ffd7316709ef9 (patch) | |
tree | c716f5cf607b5a6b1fa31cb3543063fe9d21211a | |
parent | 46aea562825715a602e073c7407c65ac4ca564c8 (diff) | |
download | jim-bot-1bad38cc81f75c90f7192989207ffd7316709ef9.tar.xz jim-bot-1bad38cc81f75c90f7192989207ffd7316709ef9.zip |
main.go: add doHomeJson(), document doHome()
-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) |