-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
56 lines (45 loc) · 1.08 KB
/
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
55
56
package main
import (
"flag"
"fmt"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"net/http"
"os"
"strings"
"sync"
)
var (
counters = make(map[string]uint64)
host = flag.String("host", "localhost", "the host to bind on")
port = flag.Int("port", 8080, "the port to bind on")
mutex sync.Mutex
)
func main() {
flag.Parse()
counterRouter := mux.NewRouter()
counterRouter.HandleFunc("/{name}", CounterHandler)
address := fmt.Sprintf("%v:%v", *host, *port)
println("Hosting at " + address)
if err := http.ListenAndServe(address, handlers.LoggingHandler(os.Stdout, counterRouter)); err != nil {
println("Error while serving: " + err.Error())
}
}
func CounterHandler(response http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
name := vars["name"]
fmt.Fprintf(response, "%v", count(name))
}
func count(name string) uint64 {
lower := strings.ToLower(name)
mutex.Lock()
defer mutex.Unlock()
var count uint64
if current, ok := counters[lower]; ok {
count = current + 1
} else {
count = 1
}
counters[lower] = count
return count
}