-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.go
More file actions
107 lines (89 loc) · 2.23 KB
/
server.go
File metadata and controls
107 lines (89 loc) · 2.23 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"net/http"
"os"
"path/filepath"
"strings"
"text/template"
)
const version = "1.0.0"
func main() {
http.HandleFunc("/", serveTemplate)
http.HandleFunc("/api/quote", quoteHandler)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.Printf("Defaulting to port %s", port)
}
fmt.Printf("Starting server at port " + port + "\n")
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
}
func getApiEndpoint() string {
endpoint := os.Getenv("APIENDPOINT")
if endpoint == "" {
endpoint = "/api/quote"
}
return endpoint
}
func serveTemplate(w http.ResponseWriter, req *http.Request) {
cleanPath := filepath.Clean(req.URL.Path)
if strings.HasSuffix(cleanPath, ".js") {
w.Header().Set("Content-Type", "text/javascript")
} else if strings.HasSuffix(cleanPath, ".css") {
w.Header().Set("Content-Type", "text/css")
} else if strings.HasSuffix(cleanPath, ".html") {
w.Header().Set("Content-Type", "html")
} else if strings.HasSuffix(cleanPath, ".ico") {
w.Header().Set("Content-Type", "image/png")
}
fp := filepath.Join("web", cleanPath)
tmpl, err := template.ParseFiles(fp)
if err == nil {
tmpl.Execute(w, map[string]string{
"api": getApiEndpoint(),
})
} else {
w.WriteHeader(404)
}
}
func quoteHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/quote" {
http.Error(w, "404 not found.", http.StatusNotFound)
return
}
if r.Method != "GET" {
http.Error(w, "Method is not supported.", http.StatusNotFound)
return
}
authors, authErr := readLines("data/authors.txt")
quotes, quoteErr := readLines("data/quotes.txt")
if authErr == nil && quoteErr == nil {
randomLine := rand.Intn(len(authors))
json := "{\"quote\": \"" + quotes[randomLine] + "\", " +
"\"author\": \"" + authors[randomLine] + "\", " +
"\"appVersion\": \"" + version + "\"" +
"}"
fmt.Fprintf(w, json)
} else {
fmt.Fprintf(w, "Error")
}
}
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}