我是 GoLang 的新手,想在 go-lang 中定義一個全局計數器來記錄對 http 服務器進行的查詢次數。我認為最簡單的方法是定義一個存儲當前計數的“全局”變量,并在每個查詢中增加它(為了方便起見,讓我們把并發問題放在一邊)。無論如何,這是我迄今為止計劃實現的代碼:package mainimport ( "fmt" "net/http")count := 0 // *Error* non-declaration statement outside function bodyfunc increment() error{ count = count + 1 return nil}func mainHandler(w http.ResponseWriter, r *http.Request){ increment() fmt.Fprint(w,count)}func main(){ http.HandleFunc("/", mainHandler) http.ListenAndServe(":8085",nil)}如您所見,count無法在那里定義var ,它與我以前使用的 Java servlet 不同。那么我怎樣才能做到這一點呢?
3 回答

FFIVE
TA貢獻1797條經驗 獲得超6個贊
計數器必須以原子方式遞增,否則您將遇到競爭條件并錯過一些計數。
聲明一個全局int64變量并使用以下sync.atomic方法訪問它:
package main
import (
"net/http"
"sync/atomic"
)
var requests int64 = 0
// increments the number of requests and returns the new value
func incRequests() int64 {
return atomic.AddInt64(&requests, 1)
}
// returns the current value
func getRequests() int64 {
return atomic.LoadInt64(&requests)
}
func handler(w http.ResponseWriter, r *http.Request) {
incRequests()
// handle the request here ...
}
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
- 3 回答
- 0 關注
- 297 瀏覽
添加回答
舉報
0/150
提交
取消