摘要
本节将使用go语言中的net/http package编写写出一个简洁的HTTP服务器。net/http servers中的一个基础概念是处理程序(handlers),处理程序是实现http.Handler接口的对象 。
正文
编写处理程序的常见方法是http.HandlerFunc
在具有适当签名的函数上使用适配器。充当处理程序的函数采用http.ResponseWriter
和http.Request
作为参数。响应编写器用于填写HTTP响应。在这里,我们的回应就是“ hello \ n”。该处理程序通过读取所有HTTP请求标头并将它们回显到响应主体中,从而使操作更加复杂。(--新消息频道)我们使用http.HandleFunc
便捷功能在服务器路由上注册处理程序 。它在程序包中设置默认路由器,net/http并接受一个函数作为参数。最后,ListenAndServe
使用端口和处理程序进行调用。nil告诉它使用我们刚刚设置的默认路由器。在后台运行服务器,并访问/hello路由。
配置Go语言运行环境
cp /share/tar/go1.12.9.linux-amd64.tar.gz .
tar -C /usr/local -xzvf go1.12.9.linux-amd64.tar.gz
echo export PATH=$PATH:/usr/local/go/bin >> /etc/profile
source /etc/profile
go version
编写Go语言http server程序
cat >> http-server.go << EOF
package main
import (
"fmt"
"net/http"
)
func hello(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "hello\n")
}
func headers(w http.ResponseWriter, req *http.Request) {
for name, headers := range req.Header {
for _, h := range headers {
fmt.Fprintf(w, "%v: %v\n", name, h)
}
}
}
func main() {
http.HandleFunc("/hello", hello)
http.HandleFunc("/headers", headers)
http.ListenAndServe(":80", nil)
}
EOF
开启服务器并进行验证
go run http-server.go &
curl localhost/hello
完结
以上就是使用Go语言编写一个简洁的HTTP服务器的所有内容,欢迎小伙伴们交流讨论。
原文地址:https://cloud.tencent.com/developer/article/2001293
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。