main.go 694 B

12345678910111213141516171819202122232425262728293031323334
  1. // Server2 is a minimal "echo" and counter server.
  2. package main
  3. import (
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "sync"
  8. )
  9. var mu sync.Mutex
  10. var count int
  11. func main() {
  12. http.HandleFunc("/", handler)
  13. http.HandleFunc("/count", counter)
  14. log.Fatal(http.ListenAndServe("localhost:8000", nil))
  15. }
  16. // handler echoes the Path component of the requested URL.
  17. func handler(w http.ResponseWriter, r *http.Request) {
  18. mu.Lock()
  19. count++
  20. mu.Unlock()
  21. fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
  22. }
  23. // counter echoes the number of calls so far.
  24. func counter(w http.ResponseWriter, r *http.Request) {
  25. mu.Lock()
  26. fmt.Println(r)
  27. fmt.Fprintf(w, "Count %d\n", count)
  28. mu.Unlock()
  29. }