-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhello.go
52 lines (43 loc) · 977 Bytes
/
hello.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
package main
import (
"fmt"
"log"
"net/http"
"sync"
)
const (
port = ":1234"
)
var calls = 0
var mutex = &sync.Mutex{}
func helloWorld(w http.ResponseWriter, r *http.Request) {
mutex.Lock()
calls++
mutex.Unlock()
log.Printf("request from %v\ncalls: %d\n", r.RemoteAddr, calls)
w.Write([]byte("howdy\n"))
}
func books(w http.ResponseWriter, r *http.Request) {
mutex.Lock()
calls++
mutex.Unlock()
log.Printf("request from %v\ncalls: %d\n", r.RemoteAddr, calls)
magazinPages := map[string]int{
"vogue": 130,
"natgeo": 78,
"newyorker": 132,
}
magazine := r.URL.Path[len("/magazine/"):]
pages := magazinPages[magazine]
if len(magazine) > 0 {
fmt.Fprintf(w, "%s has %d pages.\n", magazine, pages)
} else {
fmt.Fprintf(w, "No magazine provided.\n")
}
}
func main() {
http.HandleFunc("/", helloWorld)
http.HandleFunc("/magazine/", books)
log.Printf("Server at http://localhost%v.\n", port)
log.Fatal(http.ListenAndServe(port, nil))
}