Is the example server2 in the Go programming language book wrong?

王林
Release: 2024-02-05 23:06:08
forward
958 people have browsed it

Is the example server2 in the Go programming language book wrong?

Question content

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()
}
Copy after login

main.go

package main

import "book/server"

func main() {
    server.Run()
}
Copy after login

When I run: go run main.go and access two pages localhost:8000 and localhost:8000/count

  1. Every time I refresh the /count page, the count is incremented. Why?
  2. Whenever I refresh the / and /count pages, the displayed count increases inconsistently? Not based on the number of refreshes. Why?

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.


Correct answer


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.icoSend 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'
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!