去http服务器和全局变量

drl*_*exa 6 go

我有一个http服务器.它是用Go编写的.我有这个代码:

package main
import (
    "net/http"
    "runtime"
)
var cur = 0
func handler(w http.ResponseWriter, r *http.Request) {
    cur = cur + 1;
}
func main() {
    runtime.GOMAXPROCS(runtime.NumCPU())
    http.HandleFunc("/", handler)
    http.ListenAndServe(":9010", nil)
}
Run Code Online (Sandbox Code Playgroud)

安全吗?可能是我需要使用互斥锁?

nem*_*emo 5

不,这不安全,是的,您需要锁定某种形式。每个连接都在它自己的 goroutine 中处理。有关详细信息,请参阅Serve() 实现

一般模式是使用 goroutine 检查通道并通过通道接受更改:

var counterInput = make(chan int)

func handler(w http.ResponseWriter, r *http.Request) {
    counterInput <- 1
}

func counter(c <- chan int) {
    cur := 0
    for v := range c {
        cur += v
    }
}

func main() {
    go counter(counterInput)
    // setup http
}
Run Code Online (Sandbox Code Playgroud)

相关:“net/http”对全局变量的使用是否被认为是 golang 中的一个好习惯?.