-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
74 lines (59 loc) · 1.42 KB
/
Copy pathmain.go
File metadata and controls
74 lines (59 loc) · 1.42 KB
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
package main
import (
"fmt"
"html"
"log"
"net/http"
"os"
"github.com/daxinc/cowsayweb/cowsay"
"github.com/gorilla/mux"
)
var healthy = true
func main() {
port := getPort()
r := mux.NewRouter()
r.Use(conentTypeMiddleware)
r.HandleFunc("/", indexHandler)
r.HandleFunc("/health", healthHandler)
r.NotFoundHandler = http.HandlerFunc(notFound)
log.Printf("Server listening on %s ... ", port)
log.Fatal(http.ListenAndServe(":"+port, r))
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
quote := r.URL.Query().Get("quote")
text := cowsay.Say(quote)
fmt.Fprintf(w, cowsay.IndexHTML, html.EscapeString(quote), html.EscapeString(text))
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "OK")
}
func conentTypeMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-cache")
next.ServeHTTP(w, r)
})
}
func notFound(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, `
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Page Not Found - Cow Say</title>
</head>
<body>
<h1>Page Not found.</h1>
<a href="/">Go to Home Page</a>
</body>
</html>`)
}
func getPort() string {
port := "8080"
args := os.Args
if len(args) > 1 {
port = args[1]
}
return port
}