如何在同一软件包的两个单独文件中拆分Go Go Gorilla Mux路由



我有单独的文件路由。GO(软件包路由(,我存储所有路由和处理程序。但是我想将此文件分为两个文件。我想重命名我的路由。go到main.go,并创建新的附加文件modulex.go(软件包路由(。我怎样才能做到这一点?我想将所有路由存储在相同的"软件包路由"的多个文件中。

package routes
import (
	"github.com/gorilla/mux"
	"net/http"
	"github.com/---/001/models"
	"github.com/---/001/sessions"
	"github.com/---/001/utils"
	"github.com/---/001/middleware"
)
func NewRouter() *mux.Router {
	r := mux.NewRouter()
	r.HandleFunc("/", middleware.AuthRequired(indexGetHandler)).Methods("GET")
	r.HandleFunc("/", middleware.AuthRequired(indexPostHandler)).Methods("POST")
	r.HandleFunc("/signup", signupGetHandler).Methods("GET")
	r.HandleFunc("/signup", signupPostHandler).Methods("POST")
	r.HandleFunc("/signin", signinGetHandler).Methods("GET")
	r.HandleFunc("/signin", signinPostHandler).Methods("POST")
	r.HandleFunc("/signout", signoutGetHandler).Methods("GET")
	r.HandleFunc("/services", middleware.AuthRequired(servicesHandler)).Methods("GET")
	fs := http.FileServer(http.Dir("./static/"))
	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))
	return r
}

我想在此主文件之外移动全部"/注册"one_answers"/signin"路由和处理程序。然后以某种方式将它们传递回这个新函数。您只能为我提供一本书或一些在线示例。

您可以使用另一个修改路由器的功能。

//In another file
func addSignHandler(r *mux.Router) {
    r.HandleFunc("/signup", signupGetHandler).Methods("GET")
    r.HandleFunc("/signup", signupPostHandler).Methods("POST")
    r.HandleFunc("/signin", signinGetHandler).Methods("GET")
    r.HandleFunc("/signin", signinPostHandler).Methods("POST")
    r.HandleFunc("/signout", signoutGetHandler).Methods("GET")
}

并使用它:

func NewRouter() *mux.Router {
    r := mux.NewRouter()
    r.HandleFunc("/", middleware.AuthRequired(indexGetHandler)).Methods("GET")
    r.HandleFunc("/", middleware.AuthRequired(indexPostHandler)).Methods("POST")
    addSignHandler(r)
    r.HandleFunc("/services", middleware.AuthRequired(servicesHandler)).Methods("GET")
    fs := http.FileServer(http.Dir("./static/"))
    r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))
    return r
}

甚至更好,您可以重构代码以使其更加一致:

func addMainHandler(r *mux.Router) {
    r.HandleFunc("/", middleware.AuthRequired(indexGetHandler)).Methods("GET")
    r.HandleFunc("/", middleware.AuthRequired(indexPostHandler)).Methods("POST")
    r.HandleFunc("/services", middleware.AuthRequired(servicesHandler)).Methods("GET")
    fs := http.FileServer(http.Dir("./static/"))
    r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))
}

并将NewRouter简化为:

func NewRouter() *mux.Router {
    r := mux.NewRouter()
    addMainHandler(r)
    addSignHandler(r)
    return r
}

最新更新