方案1:使用ServeMux
package main
import (
"fmt"
"net"
"net/http"
"regexp"
)
var serveMux = new(http.ServeMux)
func main() {
serveMux.HandleFunc("/", Route)
listen, _ := net.Listen("tcp", ":8000")
fmt.Println("服务已启动:", "127.0.0.1:8000")
http.Serve(listen, serveMux)
}
type routeInfo struct {
pattern string
handler http.Handler
}
var routePath = []routeInfo{
{pattern: "^/index$", handler: index()},
{pattern: "^/hello/?$", handler: hello()},
}
func Route(w http.ResponseWriter, r *http.Request) {
isFound := false
for _, route := range routePath{
re, err := regexp.Compile(route.pattern)
if err != nil {
continue
}
if re.MatchString(r.URL.Path){
isFound = true
route.handler.(http.HandlerFunc)(w, r)
return
}
}
if !isFound{
fmt.Fprint(w, "404 Page Not Found")
}
}
func index() http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
_, _ = fmt.Fprint(writer, "这是首页")
})
}
func hello() http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
_, _ = fmt.Fprint(writer, "这是hello页面")
})
}
方案2:直接使用
package main
import (
"fmt"
"net"
"net/http"
"regexp"
)
func main() {
l, _ := net.Listen("tcp", "127.0.0.1:8080")
_ = http.Serve(l, route())
}
type routeInfo struct {
path string
handler http.HandlerFunc
}
var routePath = []routeInfo{
{path: "^/index/\\d+$", handler: index},
{path: "^/home/\\w+$", handler: home},
}
func route() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request){
for _, route := range routePath{
ok, err := regexp.Match(route.path, []byte(r.URL.Path))
if err != nil {
fmt.Println(err.Error())
}
if ok{
route.handler(w, r)
return
}
}
_, _ = w.Write([]byte("404 not found"))
}
}
func index(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("index"))
}
func home(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("home"))
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)