douye9822 2015-01-13 08:27
浏览 109
已采纳

如何在Golang HTTP服务器中定义全局计数器

I am newbie to GoLang and want to define a global counter in go-lang to record how many queries are made to the http server.

I think the simplest way is to define a 'global' variable that stored the current count, and increase it in every query (let's put the concurrence problem aside for convenient).

Any way, here is my code I planned to achieve this so far:

package main

import (
    "fmt"
    "net/http"
)

count := 0 // *Error* non-declaration statement outside function body
func 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)
}

As you can see, var count could not be defined there, It's vary from Java servlet which I formerly using.

So how can I achieve this?

  • 写回答

4条回答 默认 最新

  • dqfwcj0030 2015-01-13 08:29
    关注

    Outside of functions you cannot use the short variable declaration :=. Outside of a function to define a global variable you have to use a variable declaration (with the var keyword):

    var count int
    

    It will automatically be initialized to int's zero value which is 0.

    Links:

    Relevant sections of the Go Language Specification which I recommend you to read:

    Variable declarations

    Short variable declarations

    Note:

    Since handling of each request runs in its own goroutine, you need explicit synchronization to access the shared counter, or you have to use other synchronized means to do a proper counting.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?