From 1bad38cc81f75c90f7192989207ffd7316709ef9 Mon Sep 17 00:00:00 2001 From: Paul Duncan Date: Sat, 8 Mar 2025 00:37:24 -0500 Subject: main.go: add doHomeJson(), document doHome() --- main.go | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index c3d5ab3..22db2eb 100644 --- a/main.go +++ b/main.go @@ -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) -- cgit v1.2.3