运行一个简单的服务器,但柜台似乎增加了3个,为什么? [英] Running a simple server, but the counter seems to go up by 3, why?

查看:305
本文介绍了运行一个简单的服务器,但柜台似乎增加了3个,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有这个小服务器。目的是,如果我访问本地主机:8000 / *它应该增加计数器 1,如果我去localhost:8000 /计数,它应该显示我当前的数字计数器

一个奇怪的事情发生在于,似乎每次访问 localhost:8000 时,计数器都会升高3.所以我会去 localhost:8000 / count counter 会在3,然后I请访问 localhost:8000 ,然后再次 localhost:8000 / count 计数器现在将在6.为什么会发生?有什么奇怪的 net / http



另外,为什么当我刷新 localhost:8000 / count ,计数增加1? 计数器 func不会增加 count ,但 count 仍然上升 - 为什么呢? 处理程序是否也添加到 localhost:8000 / count 路由中?

  package main 

import(
fmt
log
net / http
sync


var mu sync.Mutex
var count int

func main(){
http.HandleFunc(/,处理程序)
http.HandleFunc(/ count,计数器)
log.Fatal(http.ListenAndServe(localhost:8000 ,nil))
}

//处理程序回显请求的URL的Path组件。
func handler(w http.ResponseWriter,r * http.Request){
mu.Lock()
count ++
mu.Unlock()
fmt.Fprintf( w,URL.Path =%q\\\
,r.URL.Path)
}

//计数器回应到目前为止的呼叫数量。
func counter(w http.ResponseWriter,r * http.Request){
mu.Lock()
fmt.Fprintf(w,Count%d \ n,count)
mu.Unlock()
}


解决方案

额外的请求是你的浏览器试图访问/favicon.ico



例如,你可以看到这个,如果你在你的处理程序中输出http.Request到标准输出funcs。


I have this little server here. The intent is that if I visit localhost:8000/* it should increase counter by 1, and if I go to localhost:8000/count, it should show me the current number of counter.

A weird thing happening is that it seems like every time I visit localhost:8000, the counter goes up by 3. So I'd go to localhost:8000/count and the counter would be at 3, and then I visit localhost:8000, and then localhost:8000/count again, counter would now be at 6. Why does that happen? Is there something weird with net/http?

Also, why is it that when I refresh localhost:8000/count, the count goes up 1 by 1? The counter func doesn't increment count, yet count still goes up - why is that? Does handler get added to the localhost:8000/count route as well?

package main

import (
        "fmt"
        "log"
        "net/http"
        "sync"
)

var mu sync.Mutex
var count int

func main() {
        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++
        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) {
        mu.Lock()
        fmt.Fprintf(w, "Count %d\n", count)
        mu.Unlock()
}

解决方案

The extra requests are your browser trying to access /favicon.ico

You can see this, for example, if you print the http.Request to stdout in your handler funcs.

这篇关于运行一个简单的服务器,但柜台似乎增加了3个,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆