I am reading "Go Programming Language Book". In Chapter 1, Server 2 Example: Book Code, mutexes are used to prevent race conditions. However, I copied the code and tried running it, but the results were inconsistent. Is the code in the example wrong?
This is how I use the code:
server.go
package server import ( "fmt" "log" "net/http" "sync" ) const ( port string = ":8000" ) var count int var mu sync.mutex func run() { http.handlefunc("/", handler) http.handlefunc("/count", counter) fmt.printf("server is listening on port: %s\n", port) log.fatal(http.listenandserve(port, nil)) } func handler(w http.responsewriter, r *http.request) { mu.lock() count++ mu.unlock() fmt.fprintf(w, "url path = %q\n", r.url.path) } func counter(w http.responsewriter, r *http.request) { mu.lock() fmt.fprintf(w, "count = %d\n", count) mu.unlock() }
main.go
package main import "book/server" func main() { server.Run() }
When I run: go run main.go and access two pages localhost:8000 and localhost:8000/count
I expected the count to only increase when I visit the / page instead of the /count page, and to increase based on how many times I refresh.
That’s because when you test a web page with a browser, most of the time, the browser will also send http://localhost: 8000/favicon.ico
Send request. See screenshot below:
/favicon.ico
does not have a dedicated handler, it matches /
and will therefore be handled by server.handler
.
It is recommended to use other tools to test such demos. For example, curl
:
$ curl 'http://localhost:8000/' $ curl 'http://localhost:8000/count'
The above is the detailed content of Is the example server2 in the Go programming language book wrong?. For more information, please follow other related articles on the PHP Chinese website!