-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecho.go
More file actions
170 lines (147 loc) · 4.63 KB
/
Copy pathecho.go
File metadata and controls
170 lines (147 loc) · 4.63 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
// MIT License
//
// Copyright (c) 2018 Yunzhu Li
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package main
import (
"crypto/sha256"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
)
var testMode = false
var srcCommit string
var apiToken string
// main initializes application and starts serving requests
func main() {
// Configuration
apiToken = os.Getenv("API_TOKEN")
port := os.Getenv("PORT")
if port == "" {
port = "8000"
}
// Routes
http.HandleFunc("/", rootHandler)
http.HandleFunc("/cache", cacheHandler)
http.HandleFunc("/cpu", cpuHandler)
http.HandleFunc("/exit", exitHandler)
http.HandleFunc("/headers", headersHandler)
http.HandleFunc("/health", healthHandler)
http.HandleFunc("/ip", ipHandler)
// Start serving
log.Println("Starting service on " + port)
log.Println("Source commit: " + srcCommit)
if !testMode {
http.ListenAndServe(":"+port, nil)
}
}
// validateAPIToken validates API token
func validateAPIToken(token string) bool {
if apiToken == "" || token != apiToken {
return false
}
return true
}
// rootHandler handles requests to /
func rootHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
fmt.Fprint(w, "<html><pre><b>routes:</b>\n"+
"/ root (this route)\n"+
"/cache returns cacheable but delayed (500ms) response\n"+
"/cpu performs CPU-intensive operation, requires API token\n"+
"/exit causes server process to exit immediately, requires API token\n"+
"/headers returns request headers in JSON\n"+
"/health returns application health info\n"+
"/ip returns client IP (uses X-Forwarded-For if present, otherwise remote IP)\n"+
"\n"+
"Include API token in X-Api-Token header.\n"+
"Source commit: "+srcCommit+"\n"+
"</pre></html>")
}
func cacheHandler(w http.ResponseWriter, r *http.Request) {
// Delayed response, but allows caching
timer := time.NewTimer(500 * time.Millisecond)
<-timer.C
w.Header().Set("Cache-Control", "public, max-age=10") // 10 seconds
// Response with current time
t := time.Now()
fmt.Fprint(w, t.Format("060102_150405"))
}
func cpuHandler(w http.ResponseWriter, r *http.Request) {
// Validate exit token
token := r.Header.Get("X-Api-Token")
if !validateAPIToken(token) {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, "Invalid API token\n")
return
}
// Handlers are already executed asynchronously
fmt.Fprint(w, cpuLoad())
}
// cpuLoad performs CPU-intensive operations
func cpuLoad() string {
for i := 0; i < 1000000; i++ {
sha256.Sum256([]byte("abc"))
}
return fmt.Sprint("")
}
func exitHandler(w http.ResponseWriter, r *http.Request) {
// Validate exit token
token := r.Header.Get("X-Api-Token")
if !validateAPIToken(token) {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, "Invalid API token\n")
return
}
// Not a graceful shutdown
log.Println("Exiting due to /exit")
os.Exit(0)
}
func headersHandler(w http.ResponseWriter, r *http.Request) {
// Join header values
headers := make(map[string]string)
for name := range r.Header {
headers[name] = r.Header.Get(name)
}
// Marshal with indent
m, _ := json.MarshalIndent(headers, "", " ")
fmt.Fprint(w, string(m))
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "ok")
}
func ipHandler(w http.ResponseWriter, r *http.Request) {
// Try to get remote IP from xff header first
remoteAddr := r.Header.Get("x-forwarded-for")
// Use client IP if no xff header
if remoteAddr == "" {
remoteAddr = r.RemoteAddr
}
// Write JSON
result := map[string]string{"remote_addr": remoteAddr}
m, _ := json.MarshalIndent(result, "", " ")
fmt.Fprint(w, string(m))
}