我正在使用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)
}
所以我想要做的就是取出并将这个路由声明拆分成多个文件,我将如何去做呢? 提前致谢。
答案 0 :(得分:7)
这样的事情怎么样?
//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")
}
}
答案 1 :(得分:5)
您可以将路由器独立地模块化为不同的软件包,然后将其安装在主路由器上
仅对以下issue进行详细说明,您可以提出这种方法,使其具有相当的可扩展性(在某种程度上更易于测试)
/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"))
}
答案 2 :(得分:3)
我喜欢查看github中的其他项目以获取有关如何处理内容的想法,对于这些情况,我通常首先查看Docker repo。这就是他们这样做的方式:
对于system的路由,在system_routes.go中定义所有处理程序,然后在system.go中的NewRouter函数上初始化这些路由。
type systemRouter struct {
backend Backend
routes []router.Route
}
func NewRouter(b Backend) router.Router {
r := &systemRouter{
backend: b,
}
r.routes = []router.Route{
local.NewOptionsRoute("/", optionsHandler),
local.NewGetRoute("/_ping", pingHandler),
local.NewGetRoute("/events", r.getEvents),
local.NewGetRoute("/info", r.getInfo),
local.NewGetRoute("/version", r.getVersion),
local.NewPostRoute("/auth", r.postAuth),
}
return r
}
// Routes return all the API routes dedicated to the docker system.
func (s *systemRouter) Routes() []router.Route {
return s.routes
}
请注意,systemRouter实现router.Router接口,Routes函数返回[] router.Route,其处理程序定义为
func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error
而不是Go的标准http处理程序:
func(w http.ResponseWriter, r *http.Request)
因此,在makeHttpHandler函数中有一个额外的代码可以将Docker API处理程序转换为Go HTTP处理程序。
最后,要将这些路由添加到他们的mux路由器,在他们的server.go上,他们将add middleware的其他几个函数实现给他们的处理程序。
如果你认为这是你正在寻找的东西,那么花点时间分析他们路线的Docker代码,如果你需要我详细说明或者我错过了什么,发表评论。