Skip to content

Instantly share code, notes, and snippets.

@rayning0
Created May 30, 2017 14:38
Show Gist options
  • Select an option

  • Save rayning0/d214dfbd6a56cab8204057da69e23cd0 to your computer and use it in GitHub Desktop.

Select an option

Save rayning0/d214dfbd6a56cab8204057da69e23cd0 to your computer and use it in GitHub Desktop.
// Server2 is a minimal "echo" and counter server.
package main
import (
"fmt"
"log"
"net/http"
"sync"
)
var mu sync.Mutex
var count int
func main() {
// strangely, when I first tried this it would call
// "handler" TWICE every time I did http://localhost:8000 in browser,
// increasing count twice. it would also call both
// "counter" AND "handler" every time I did http://localhost:8000/count,
// increasing count by 1 for /count.
// http://localhost:8000 should only increase count by 1
// http://localhost:8000/count should NOT change count at all
// now it works fine, but what went wrong? (mutex has nothing to do with the error)
http.HandleFunc("/", handler)
http.HandleFunc("/count", counter)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
// handler echoes the Path component of the requested URL.
func handler(w http.ResponseWriter, r *http.Request) {
mu.Lock()
count++
fmt.Println("in handler")
fmt.Fprintf(w, "Increment Count %d\n", count)
mu.Unlock()
fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
}
// // counter echoes the number of calls so far.
func counter(w http.ResponseWriter, r *http.Request) {
fmt.Println("in counter")
mu.Lock()
fmt.Fprintf(w, "Count %d\n", count)
mu.Unlock()
}
//!-
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment