HTTP服务器,通过URL接口输出请求次数

4年以前  |  阅读数:196 次  |  编程语言:Golang 

Server2 is a minimal "echo" and counter server.

package main

import (
    "fmt"
    "log"
    "net/http"
    "sync"
)

var mu sync.Mutex
var count int

func main() {
    http.HandleFunc("/", handler)
    http.HandleFunc("/count", counter)
    log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

// handler echoes the Path component of the requested URL.
func handler(w http.ResponseWriter, r *http.Request) {
    mu.Lock()
    count++
    mu.Unlock()
    fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
}

// counter echoes the number of calls so far.
func counter(w http.ResponseWriter, r *http.Request) {
    mu.Lock()
    fmt.Fprintf(w, "Count %d\n", count)
    mu.Unlock()
}
 相关文章:
处理摄氏与华氏温度转换
Golang官方的HelloWorld
使用包tempconv进行摄氏与华氏温度的转换
并发的使用http.get获取内容,并打印出时间与内容
使用strings包方法,计算文件名
使用flag包打印命令行
HTTP服务器,返回请求参数及HTTP头部
打印所有的命令行参数
统计并打印输入的内容
读取通过命令行传入的文件,打印多次出现的行
最小HTTP服务器
使用strings.Join打印所有的命令行参数
格式化输出,打印水的温度
字符串运算示例之输出文件名
从文件或标准输入中读取内容,统计并打印出现多次的行
HTTP服务器,通过URL接口输出请求次数