blob: 22db2eb1cd7a55872195dc4e34f56d4f7d56c30e (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
// 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)
}
|