San*_*rya 2 concurrency webserver mutex go error-correction
我正在阅读《Go 编程语言》书籍。在第 1 章,服务器 2 示例中:书籍代码中,互斥体用于防止竞争条件。但是,我复制了代码并尝试运行它,但结果不一致。例子中的代码有错吗?
这是我使用代码的方式:
服务器.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()
}
Run Code Online (Sandbox Code Playgroud)
主程序
package main
import "book/server"
func main() {
server.Run()
}
Run Code Online (Sandbox Code Playgroud)
当我运行时: go run main.go 并访问两个页面 localhost:8000 和 localhost:8000/count
我预计计数只会在我访问 / 页面而不是 /count 页面时增加,并且会根据我所做的刷新次数而增加。
那是因为当你用浏览器测试网页时,大多数时候,浏览器也会发送请求http://localhost:8000/favicon.ico。请参阅下面的屏幕截图:
没有专门的处理程序/favicon.ico,并且它匹配/,因此它将由 处理server.handler。
建议使用其他工具来测试此类演示。例如,curl:
$ curl 'http://localhost:8000/'
$ curl 'http://localhost:8000/count'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
97 次 |
| 最近记录: |