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?