Go搭建http服务测试-统计访问次数(VSCode for mac)
package main
import (
"fmt"
"log"
"net/http"
"sync"
)
func main() {
http.HandleFunc("/", handler_func)
http.HandleFunc("/count", counter_func)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
var mu sync.Mutex
var count int
func handler_func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
count++
mu.Unlock()
fmt.Fprintf(w, "URL.Path=%q\n", r.URL.Path)
}
func counter_func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
fmt.Fprintf(w, "Count %d\n", count)
mu.Unlock()
}
运行服务后,访问本地的URL结果如下