dououde4065 2017-06-06 11:04
浏览 45
已采纳

跨软件包共享大猩猩/多路复用器路由器

I'm having some issues with implementing a slight MVC design with gorilla/mux.

The layout of the modules is as follows:

main.go
-- controllers
---- base.controller.go
---- example.controller.go
-- models
---- base.model.go
---- example.controller.go

All the files in controllers is in the controllers package, same with models and then the main.go is the main package.

Currently I'm just trying to get the Base Controller to be able to be shared with the main package which is working, although it's throwing some errors when trying to implement routes. The build is not throwing any errors, but the routes are not available. If I implement the Walk function in the Gorilla/Mux documentation to print out all the registered routes for the mux.Router then it gives me this error:

&{%!!(MISSING)s(*mux.Router=&{ [0xc4200901b0] map[] true false false false}) %!!(MISSING)s(http.HandlerFunc=0xc8df0) [%!!(MISSING)s(*mux.routeRegexp=&{/ false false true false 0xc420095360 / [] []})] %!!(MISSING)s(*mux.routeRegexpGroup=&{ 0xc420016240 []}) %!!(MISSING)s(bool=true) %!!(MISSING)s(bool=false) %!!(MISSING)s(bool=false) %!!(MISSING)s(bool=false) %!!(MISSING)s(mux.BuildVarsFunc=)}

The reasoning for the global var V1Router *mux.Router is firstly to access it in the main package and also to create subrouters in the other controllers.

I am fairly new to Go, but I'm trying my best to learn the best practices! Any help would be greatly appreciated!

Example code below:

base.controllers.go

package controllers

import (
        "fmt"
        "bytes"
        "net/http"
        "github.com/gorilla/mux"
)

var V1Router *mux.Router

func init () {
    V1Router = mux.NewRouter()
    V1Router.StrictSlash(true)
    V1Router.HandleFunc("/", BaseHandler)    
}

// Base route to access the API Documentation.
func BaseHandler (w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello, Gophers!")
}

main.go

package main

import (
    "net/http"
    "log"
    "github.com/projectrepo/project/models"
    "github.com/projectrepo/project/controllers"
    "github.com/gorilla/mux"
)

func main () {
    http.Handle("/v1", controllers.V1Router)
    if err := http.ListenAndServe(":8000", nil); err != nil {
        log.Fatal("Serving error.")
    }
}

In response to the comments, I tried this solution with the same result:

package main

import (
    "net/http"
    "log"
    "github.com/projectrepo/project/models"
    "github.com/projectrepo/project/controllers"
    "github.com/gorilla/mux"
)

func main () {
    r := mux.NewRouter()
    r.Handle("/v1", controllers.V1Router)
    if err := http.ListenAndServe(":8000", r); err != nil {
        log.Fatal("Serving error.")
    }
}
  • 写回答

1条回答 默认 最新

  • dtrvzd1171 2017-06-06 13:42
    关注

    Gorilla mux.Router is supposed to be used to create mapping between a set of predefined rules (e.g. host, path, protocol, scheme, etc...) and it's handler (http.Handler or http.HandlerFunc). Gorilla mux can be used to replace standard server mux. If you combine gorilla/mux with built in http server mux as your original question, i.e.

    func main () {
        http.Handle("/v1", controllers.V1Router)
        if err := http.ListenAndServe(":8000", nil); err != nil {
            log.Fatal("Serving error.")
        }
    }
    

    what actually happen when a client access /v1 is controllers.V1Router will be called with request path /v1 passed to V1Router1. In the controllers.V1Router, you defined that / will be handled by BaseHandler. However, since incoming request path is /v1, it won't match to your routing table. If you want to define sub routing, you can do as follows (this is what I mean in first comment):

    func main () {
        r := mux.NewRouter()
        v1 := r.PathPrefix("/v1").Subrouter()
        controllers.RegisterHandlers(v1)
    
        if err := http.ListenAndServe(":8000", r); err != nil {
            log.Fatal("Serving error.")
        }
    }
    

    Then in the controllers (base.controllers.go) define

    //Register handlers and it's sub router
    func RegisterHandlers(r *mux.Router) {
        //base handler, i.e. /v1
        r.StrictSlash(true)
        r.HandleFunc("/", BaseHandler)
    
        //example sub-router, i.e. /v1/example
        ex := r.PathPrefix("/example").Subrouter()
        ex.HandleFunc("/", ExampleHandler)
    
        //other handlers...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?