tk域名官方网站,合肥建设网站的公司,东莞有什么公司,山西太原门户网站开发公司Go语言基本的Web服务器实现
Go 语言中的 http 包提供了创建 http 服务或者访问 http 服务所需要的能力#xff0c;不需要额外的依赖。 Go语言在Web服务器中主要使用到了 “net/http” 库函数#xff0c;通过分析请求的URL来实现参数的接收。 下面介绍了http 中Web应用的基本…Go语言基本的Web服务器实现
Go 语言中的 http 包提供了创建 http 服务或者访问 http 服务所需要的能力不需要额外的依赖。 Go语言在Web服务器中主要使用到了 “net/http” 库函数通过分析请求的URL来实现参数的接收。 下面介绍了http 中Web应用的基本操作主要包括路由器的定义、路由的设备、请求参数的提取。
package mainimport (fmtlognet/httpsync
)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()countfmt.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?k2