Go语言基本的Web服务器实现
Go 语言中的 http 包提供了创建 http 服务或者访问 http 服务所需要的能力,不需要额外的依赖。
Go语言在Web服务器中主要使用到了 “net/http” 库函数,通过分析请求的URL来实现参数的接收。
下面介绍了http 中Web应用的基本操作,主要包括路由器的定义、路由的设备、请求参数的提取。
package mainimport ("fmt""log""net/http""sync"
)var mu sync.Mutex
var count intfunc main() {//定义路由http.HandleFunc("/", handler)http.HandleFunc("/counter", counter)http.HandleFunc("/parse", reParse)log.Fatal(http.ListenAndServe("localhost:8081", nil))
}//接口处理函数
func handler(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "respons = %s", "Hello Jack!")
}//存在多线程的公有变量时,需要使用锁来确保数据的安全。
func counter(w http.ResponseWriter, r *http.Request) {mu.Lock()count++fmt.Fprintf(w, "counter = %d", count)mu.Unlock()
}//通过获取*http.Request请求参数来分析出用户请求
func reParse(w http.ResponseWriter, r *http.Request) {parse := r.URL.Query()fmt.Fprintf(w, "parse = %s", parse)
}//输入://输出://URL: http://127.0.0.1:8081///URL: http://127.0.0.1:8081/counter//URL: http://127.0.0.1:8081/parse?k=2