-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathserver.go
More file actions
57 lines (45 loc) · 1.22 KB
/
server.go
File metadata and controls
57 lines (45 loc) · 1.22 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
package main
import (
"fmt"
"log"
"net/http"
"os"
)
type appConfig struct {
logger *log.Logger
}
type app struct {
config appConfig
handler func(w http.ResponseWriter, r *http.Request, config appConfig)
}
func (a app) ServeHTTP(w http.ResponseWriter, r *http.Request) {
a.handler(w, r, a.config)
}
func apiHandler(w http.ResponseWriter, r *http.Request, config appConfig) {
config.logger.Println("Handling API request")
fmt.Fprintf(w, "Hello, world!")
}
func healthCheckHandler(w http.ResponseWriter, r *http.Request, config appConfig) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
config.logger.Println("Handling healthcheck request")
fmt.Fprintf(w, "ok")
}
func setupHandlers(mux *http.ServeMux, config appConfig) {
mux.Handle("/healthz", &app{config: config, handler: healthCheckHandler})
mux.Handle("/api", &app{config: config, handler: apiHandler})
}
func main() {
listenAddr := os.Getenv("LISTEN_ADDR")
if len(listenAddr) == 0 {
listenAddr = ":8080"
}
config := appConfig{
logger: log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lshortfile),
}
mux := http.NewServeMux()
setupHandlers(mux, config)
log.Fatal(http.ListenAndServe(listenAddr, mux))
}