/
simple-webserver.go
69 lines (56 loc) · 1.33 KB
/
simple-webserver.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// my-go-examples simple-webserver.go
package main
import (
"fmt"
"io"
"log"
"net/http"
)
const (
ip = "127.0.0.1"
port = "1234"
)
const htmlMonkeyIndex = `
<html>
<body>
<p> You are in the monkeyHandler </p>
<a href="/jeff">Goto /jeff</a>
</body>
</html>
`
// rootHandler
func rootHandler(res http.ResponseWriter, req *http.Request) {
// print out the req struct for fun
fmt.Printf("req is %+v\n\n", req.URL)
io.WriteString(res, "You are in the rootHandler\n")
io.WriteString(res, "hello, world!\n")
}
// jeffHandler
func jeffHandler(res http.ResponseWriter, req *http.Request) {
// print out the req struct for fun
fmt.Printf("req is %+v\n\n", req.URL)
io.WriteString(res, "You are in the jeffHandler\n")
io.WriteString(res, "hello, Jeff!\n")
}
// monkeyHandler
func monkeyHandler(res http.ResponseWriter, req *http.Request) {
// print out the req struct for fun
fmt.Printf("req is %+v\n\n", req.URL)
fmt.Fprintf(res, htmlMonkeyIndex)
}
func startServer() {
// LISTEN ON IP AND PORT
fmt.Printf("\nListening on %s:%s\n\n", ip, port)
log.Fatal(http.ListenAndServe(ip+":"+port, nil))
}
func main() {
// HANDLER
http.HandleFunc("/", rootHandler)
http.HandleFunc("/jeff", jeffHandler)
http.HandleFunc("/monkey", monkeyHandler)
// START WEBSERVER
go startServer()
// PRESS RETURN TO EXIT
fmt.Scanln()
fmt.Println("done")
}