使用 net/http
包编写一个基本的 HTTP 服务器很容易。
package main
import (
"fmt"
"net/http"
)
// net/http 服务器中的一个基本概念是处理程序。处理程序是实现 http.Handler 接口的对象。编写处理程序的一种常见方法是在具有适当签名的函数上使用 http.HandlerFunc
func hello(w http.ResponseWriter, req *http.Request) {
// 作为处理程序的函数以 http.ResponseWriter 和 http.Request 作为参数。响应写入器用于填充 HTTP 响应。在这里,我们的简单响应只是 "hello\\n"。
fmt.Fprintf(w, "hello\\n")
}
func headers(w http.ResponseWriter, req *http.Request) {
// 这个处理程序做了一些更复杂的事情,它读取所有 HTTP 请求头并将它们回显到响应主体中。
for name, headers := range req.Header {
for _, h := range headers {
fmt.Fprintf(w, "%v: %v\\n", name, h)
}
}
}
func main() {
// 我们使用 http.HandleFunc 便捷函数在服务器路由上注册我们的处理程序。它设置了 net/http 包中的默认路由器,并将一个函数作为参数。
http.HandleFunc("/hello", hello)
http.HandleFunc("/headers", headers)
http.ListenAndServe(":8090", nil)
}
运行结果:
➜ go run http-server.go
➜ curl <http://localhost:8090/hello>
hello
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。