-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
54 lines (45 loc) · 925 Bytes
/
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
//go:generate stringer -type=Color
package main
import (
"fmt"
"log"
"math/rand"
"net/http"
"os"
"time"
)
var version = "v2"
const (
_ Color = iota
red
blue
yellow
pink
white
)
type Color int
var color Color
func main() {
port := ":" + getPort()
s := rand.NewSource(time.Now().UnixNano())
r := rand.New(s)
color = Color(r.Intn(5))
http.HandleFunc("/", indexHandler)
fmt.Printf("Starting server at %s\n", port)
fmt.Println("Press ctrl-c to terminate...")
log.Fatal(http.ListenAndServe(port, nil))
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
host, err := os.Hostname()
if err != nil {
fmt.Println(err)
}
fmt.Fprintf(w, "<!DOCTYPE html><html><h2>Simple Go Web Server %s</h2><body style='background-color: %s'> Running on %s</body></html>", version, color.String(), host)
}
func getPort() string {
port := os.Getenv("PORT")
if port == "" {
return "8080"
}
return port
}