使用net/http可快速构建Web服务器。1. 调用http.HandleFunc注册路由,如"/"映射helloHandler;2. 通过http.ListenAndServe(":8080", nil)启动服务;3. 可注册多个处理器处理不同路径;4. 使用http.NewServeMux实现自定义路由;5. 结合http.FileServer和http.StripPrefix提供静态文件服务。

用Golang的
net/http
net/http
使用
http.ListenAndServe
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, 世界!")
}
func main() {
http.HandleFunc("/", helloHandler)
fmt.Println("服务器运行在 http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
说明:
http.HandleFunc
helloHandler
helloHandler
http.ResponseWriter
*http.Request
http.ListenAndServe(":8080", nil)nil
DefaultServeMux
你可以注册多个路径来响应不同的URL:
立即学习“go语言免费学习笔记(深入)”;
func aboutHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "这是关于页面。")
}
func main() {
http.HandleFunc("/", helloHandler)
http.HandleFunc("/about", aboutHandler)
fmt.Println("服务器运行在 http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
访问
/
/about
为了更好的控制,可以创建自己的
http.ServeMux
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", helloHandler)
mux.HandleFunc("/about", aboutHandler)
fmt.Println("服务器运行在 http://localhost:8080")
http.ListenAndServe(":8080", mux)
}
使用自定义mux可以避免与其他包注册的路由冲突,也更清晰地管理路由逻辑。
使用
http.FileServer
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", helloHandler)
mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
fmt.Println("服务器运行在 http://localhost:8080")
http.ListenAndServe(":8080", mux)
}
说明:
static/
style.css
image.png
http.FileServer(http.Dir("static/"))http.StripPrefix
/static/
/static/style.css
static/style.css
基本上就这些。用
net/http
以上就是如何使用Golang的net/http包从零开始构建一个简单的Web服务器的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号