Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Go路由注册

Go路由注册方法详解

作者:枕石zs

Go语言中,http.NewServeMux()和http.HandleFunc()是两种不同的路由注册方式,前者创建独立的ServeMux实例,适合模块化和分层路由,灵活性高,但启动服务器时需要显式指定,后者使用全局默认的http.DefaultServeMux,适合简单场景,感兴趣的朋友跟随小编一起看看吧

Go路由注册方法

mux := http.NewServeMux()http.HandleFunc 是 Go 语言中两种不同的路由注册方式,它们的区别主要体现在以下几个方面:

1. 路由注册的方式

http.NewServeMux():

mux := http.NewServeMux()
mux.HandleFunc("/", rootHandler)
mux.HandleFunc("/about", aboutHandler)

http.HandleFunc():

http.HandleFunc("/", homeHandler)
http.HandleFunc("/about", aboutHandler)

2. 路由器的独立性

http.NewServeMux():

mux1 := http.NewServeMux()
mux1.HandleFunc("/api/v1", apiV1Handler)
mux2 := http.NewServeMux()
mux2.HandleFunc("/api/v2", apiV2Handler)
// 组合多个路由器
mainMux := http.NewServeMux()
mainMux.Handle("/v1/", mux1)
mainMux.Handle("/v2/", mux2)

http.HandleFunc():

3. 灵活性

http.NewServeMux():

mux := http.NewServeMux()
mux.HandleFunc("/", rootHandler)
mux.HandleFunc("/admin", adminHandler)
// 使用中间件
loggedMux := loggingMiddleware(mux)
http.ListenAndServe(":8080", loggedMux)

http.HandleFunc():

4. 启动服务器的方式

http.NewServeMux():

mux := http.NewServeMux()
mux.HandleFunc("/", rootHandler)
http.ListenAndServe(":8080", mux)

http.HandleFunc():

http.HandleFunc("/", homeHandler)
http.ListenAndServe(":8080", nil) // 使用默认的 ServeMux

5. 适用场景

http.NewServeMux():

http.HandleFunc():

6. 代码示例对比

使用 http.NewServeMux()

package main
import (
	"fmt"
	"net/http"
)
func rootHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Root Handler")
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "About Handler")
}
func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", rootHandler)
	mux.HandleFunc("/about", aboutHandler)
	fmt.Println("Server is running on http://localhost:8080")
	http.ListenAndServe(":8080", mux)
}

使用 http.HandleFunc()

package main
import (
	"fmt"
	"net/http"
)
func homeHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Home Handler")
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "About Handler")
}
func main() {
	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/about", aboutHandler)
	fmt.Println("Server is running on http://localhost:8080")
	http.ListenAndServe(":8080", nil)
}

总结

特性http.NewServeMux()http.HandleFunc()
路由器实例自定义 ServeMux 实例使用全局默认的 http.DefaultServeMux
灵活性高,支持模块化和分层路由低,适合简单场景
适用场景大型项目或需要复杂路由配置的项目小型项目或快速原型开发
启动服务器方式需要显式指定自定义 ServeMux无需显式指定,默认使用全局路由器

根据项目需求选择合适的方式:如果需要灵活性和模块化,推荐使用 http.NewServeMux();如果项目简单且不需要复杂配置,可以使用 http.HandleFunc()

到此这篇关于Go路由注册方法的文章就介绍到这了,更多相关Go路由注册内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文