我正在嘗試計算每個新的動態 URL
var count int
// *Error* non-declaration statement outside function body
func increment() error {
count = count 1
return nil
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
m := make(map[string]int)
if r.Method != "POST" {
http.Error(w, "Method is not supported.", http.StatusNotFound)
return
}
increment()
b, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
urlPath := r.RequestURI
value, ok := m[urlPath]
if ok {
m[urlPath] = count 1
fmt.Println("value: ", value)
} else {
m[urlPath] = count
fmt.Println(m)
fmt.Println("key not found")
}
fmt.Println(m)
fmt.Fprintf(w, "Hello!", count)
fmt.Printf("%s", b)
}
func main() {
http.HandleFunc("/report/", helloHandler) // Update this line of code
fmt.Printf("Starting server at port 8080\n")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
結果應該以所有 URL 作為鍵和次數作為值進行映射,例如: {"abc" : 2 "foo" : 1 "ho": 5} 但是當我每次運行我的代碼時,鍵再次更新
uj5u.com熱心網友回復:
有多個問題:
您在每次執行處理程式函式時創建一個新映射。
由于 HTTP 處理程式在同時運行的單獨 goroutine 上執行,因此您在全域
counter變數上存在資料競爭。
我不確定我是否正確決議了您所追求的內容,但據說您應該:
- 擁有一張全球地圖。
- 使對該映射的每次訪問都受到互斥鎖的保護。
- 遞增計數器,它們是地圖中的值。
像這樣的東西:
var (
hitsMu sync.Mutex
hits = make(map[string]*int)
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
// ...
hitsMu.Lock()
defer hitsMu.Unlock()
counterPtr := hits[urlPath]
if counterPtr == nil {
counterPtr = new(int)
hits[urlPath] = counterPtr
}
*counterPtr = 1
// ...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/419705.html
標籤:
