Go语言通过net/http包可快速构建HTTP服务器,示例代码展示用几行实现服务启动与路由注册;使用http.ServeMux可管理多路径路由,支持前缀与精确匹配;对于复杂需求,推荐集成gorilla/mux库,实现带参数、正则约束和方法限定的路由;通过函数包装可实现中间件,如日志、认证等,支持链式调用;整体设计简洁灵活,兼顾开发效率与性能。

在Go语言中构建HTTP服务器非常简单,标准库
net/http
Go通过
net/http
示例:
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
http.ListenAndServe
立即学习“go语言免费学习笔记(深入)”;
默认的
http.DefaultServeMux
http.ServeMux
示例:
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
w.Write([]byte("获取用户列表"))
} else {
http.Error(w, "方法不支持", http.StatusMethodNotAllowed)
}
})
mux.HandleFunc("/api/users/create", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
w.Write([]byte("创建用户"))
} else {
http.Error(w, "请使用POST请求", http.StatusMethodNotAllowed)
}
})
http.ListenAndServe(":8080", mux)
}
http.ServeMux
/api/
对于更复杂的路由需求,如动态路径参数、正则匹配、方法约束等,推荐使用
gorilla/mux
安装:
go get github.com/gorilla/mux
使用示例:
import "github.com/gorilla/mux"
func main() {
r := mux.NewRouter()
r.HandleFunc("/users/{id:[0-9]+}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
userID := vars["id"]
fmt.Fprintf(w, "用户ID: %s", userID)
}).Methods("GET")
r.HandleFunc("/users", createUser).Methods("POST")
http.ListenAndServe(":8080", r)
}
这里通过
{id:[0-9]+}Methods()
Go的中间件可通过函数包装实现。定义一个接收
http.Handler
http.Handler
示例:日志中间件
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("[%s] %s %s\n", r.Method, r.URL.Path, r.RemoteAddr)
next.ServeHTTP(w, r)
})
}
// 使用
r := mux.NewRouter()
r.Use(loggingMiddleware)
中间件可以链式调用,适用于认证、日志、CORS等通用逻辑。
基本上就这些。Go的HTTP服务设计简洁而灵活,从标准库起步,按需引入功能更强的路由方案,能很好地平衡开发效率与运行性能。
以上就是GolangHTTP服务器开发及路由处理方法的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号