Go语言通过net/http标准库可快速搭建Web服务器,使用http.HandleFunc注册路由并调用http.ListenAndServe启动服务;支持静态文件服务、HTTP方法判断与表单处理,并可通过http.Server自定义配置超时和TLS等参数,适用于大多数轻量级Web场景。

Go语言通过标准库net/http提供了简单高效的Web服务支持,无需引入第三方框架即可快速搭建一个基础Web服务器。核心在于注册路由处理函数并启动HTTP服务监听端口。
使用http.HandleFunc注册路径对应的处理函数,再调用http.ListenAndServe启动服务。
示例代码:
package main
import (
"net/http"
"log"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, 你好!"))
}
func main() {
http.HandleFunc("/", helloHandler)
log.Println("服务器启动在 :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
访问http://localhost:8080即可看到返回内容。
立即学习“go语言免费学习笔记(深入)”;
使用http.FileServer可以轻松提供静态资源访问,比如HTML、CSS、JS或图片文件。
示例:将./static目录作为静态资源根目录
func main() {
fs := http.FileServer(http.Dir("./static/"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("这是首页"))
})
log.Println("服务器启动在 :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
访问/static/image.png会返回./static/image.png文件。
在处理函数中通过r.Method判断请求类型,分别处理GET、POST等请求。
示例:
func formHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
w.Write([]byte(`<form method="post"><input type="text" name="name"><button>提交</button></form>`))
} else if r.Method == "POST" {
r.ParseForm()
name := r.Form.Get("name")
w.Write([]byte("你好," + name + "!"))
}
}
注意调用ParseForm()解析表单数据。
使用http.Server结构体可更精细控制服务行为,如设置超时、TLS等。
示例:
server := &http.Server{
Addr: ":8080",
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 30 * time.Second,
}
log.Fatal(server.ListenAndServe())
这种写法适合需要配置生产环境参数的场景。
基本上就这些。net/http足够应对大多数简单Web服务需求,结构清晰,性能良好,是Go语言的一大优势。不复杂但容易忽略细节,比如表单解析和路径前缀处理。
以上就是Golang使用net/http搭建Web服务器的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号