我正在使用Gorilla Mux编写REST API,我在组织路由时遇到问题,目前我的所有路由都在这样的main.go
文件中定义
//main.go package main import ( "NovAPI/routes" "fmt" "github.com/gorilla/mux" "net/http" ) func main() { router := mux.NewRouter().StrictSlash(true) router.HandleFunc("/hello", func(res http.ResponseWriter, req *http.Request) { fmt.Fprintln(res, "Hello") }) router.HandleFunc("/user", func(res http.ResponseWriter, req *http.Request) { fmt.Fprintln(res, "User") }) router.HandleFunc("/route2", func(res http.ResponseWriter, req *http.Request) { fmt.Fprintln(res, "Route2") }) router.HandleFunc("/route3", func(res http.ResponseWriter, req *http.Request) { fmt.Fprintln(res, "Route3") }) // route declarations continue like this http.ListenAndServe(":1128", router) }
所以我想要做的是取出并将这个路由声明拆分成多个文件,我将如何去做呢?提前致谢.
您可以将路由器独立地模块化为不同的软件包,然后将其安装在主路由器上
在以下问题上仅作一些详细说明,您可以提出这种方法,使其具有相当的可扩展性(在某种程度上更易于测试)
/api/router.go
package api
import (
"net/http"
"github.com/gorilla/mux"
)
func Router() *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/", home)
return router
}
func home(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("hello from API"))
}
/main.go
package main
import (
"log"
"net/http"
"strings"
"github.com/...yourPath.../api"
"github.com/...yourPath.../user"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/", home)
mount(router, "/api", api.Router())
mount(router, "/user", user.Router())
log.Fatal(http.ListenAndServe(":8080", router))
}
func mount(r *mux.Router, path string, handler http.Handler) {
r.PathPrefix(path).Handler(
http.StripPrefix(
strings.TrimSuffix(path, "/"),
handler,
),
)
}
func home(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("Home"))
}
这样的事情怎么样?
//main.go package main import ( "NovAPI/routes" "fmt" "github.com/gorilla/mux" "net/http" ) func main() { router := mux.NewRouter().StrictSlash(true) router.HandleFunc("/hello", HelloHandler) router.HandleFunc("/user", UserHandler) router.HandleFunc("/route2", Route2Handler) router.HandleFunc("/route3", Route3Handler) // route declarations continue like this http.ListenAndServe(":1128", router) } func HelloHandler(res http.ResponseWriter, req *http.Request) { fmt.Fprintln(res, "Hello") } func UserHandler(res http.ResponseWriter, req *http.Request) { fmt.Fprintln(res, "User") } func Route2Handler(res http.ResponseWriter, req *http.Request) { fmt.Fprintln(res, "Route2") } func Route3Handler(res http.ResponseWriter, req *http.Request) { fmt.Fprintln(res, "Route3") }
这样您就可以将处理程序放在其他文件中,甚至是其他包中.
如果你最终使用像数据库这样的附加依赖项,你甚至可以使用构造函数技巧来避免使用全局变量:
//main.go func main() { db := sql.Open(…) //... router.HandleFunc("/hello", NewHelloHandler(db)) //... } func NewHelloHandler(db *sql.DB) func(http.ResponseWriter, *http.Request) { return func(res http.ResponseWriter, req *http.Request) { // db is in the local scope, and you can even inject it to test your // handler fmt.Fprintln(res, "Hello") } }