-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
77 lines (60 loc) · 1.52 KB
/
main.go
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"io/ioutil"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
)
const port = "8080"
const txtPath, imagePath = "message.txt", "message.png"
var message string
func init() {
loadMessage()
}
func main() {
r := mux.NewRouter()
r.Path("/").HandlerFunc(homeHandler)
r.Path("/image.png").HandlerFunc(imageHandler)
r.Path("/message").HandlerFunc(messageHandler).Methods("POST")
srv := &http.Server{
Handler: r,
Addr: "0.0.0.0:" + port,
WriteTimeout: 10 * time.Second,
ReadTimeout: 10 * time.Second,
}
log.Printf("Listening on :%s", port)
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalln("Could not start origin server:", err)
}
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("homeHandler")
w.WriteHeader(http.StatusOK)
homeTemplate.Execute(w, struct{Message string}{message})
}
func imageHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, imagePath)
}
func messageHandler(w http.ResponseWriter, r *http.Request) {
message = r.FormValue("message")
log.Printf("messageHandler: %s", message)
Draw(message)
saveMessage()
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func loadMessage() {
content, err := ioutil.ReadFile(txtPath)
if err != nil {
message = "Hello!"
return
}
message = string(content)
log.Printf("message loaded from file: %s", message)
}
func saveMessage() {
err := ioutil.WriteFile(txtPath, []byte(message), 0644)
if err != nil {
log.Printf("error saving message: %s", err)
}
}