在外部包中注册Golang gorilla / mux路线

时间:2017-06-07 16:51:43

标签: go gorilla

在我的API中,每个路径都会有很多完全独立的处理程序,例如" / api / v1 / handler_one"和" / api / v1 / handler_two"。我试图将每个处理程序都放在它自己的软件包中,以便于维护。

我添加了一个例子。它没有工作,因为它甚至没有加载" handlers / handler_one.go"。我错过了什么?

main.go

package main

import (
    "net/http"
    "git/myapp/router"
)

func main() {

  myRouter := router.APIRouter

    srv := &http.Server{
        Handler: myRouter,
        Addr:    "0.0.0.0:8080",
    }

    log.Fatal(srv.ListenAndServe())
}

路由器/ router.go

package router

import (
    "github.com/gorilla/mux"
)

var Router = mux.NewRouter().StrictSlash(true)
var APIRouter = Router.PathPrefix("/api/v1").Subrouter()

处理程序/ handler_one.go

package handler_one

import (
    "git/myapp/router"
)

type Route struct {
    Name        string
    Method      string
    Pattern     string
    HandlerFunc http.HandlerFunc
}

type APIRoutes []Route

var apiRoutes = APIRoutes{
    Route{ "OneIndex", "GET", "/one", OneIndex, },
}

func init() {
    // Register routes
    for _, route := range apiRoutes {
        var handler http.Handler

        handler = route.HandlerFunc
        handler = Logger(handler, route.Name)

        router.APIRouter.
            Methods(route.Method).Path(route.Pattern).Name(route.Name).Handler(handler)
    }
}

// OneIndex is handling the requests to /api/v1/one
func OneIndex(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    w.WriteHeader(http.StatusOK)

  fmt.Println("Doing something...")
}

1 个答案:

答案 0 :(得分:1)

  

它没有工作,因为它甚至没有加载" handlers / handler_one.go"

您的意思是init中的handlers/handler_one.go函数未被执行吗?

这是预期的,因为在您粘贴的代码中,您没有在任何地方导入该包。

尝试在main.go中导入该包。

如果导入它的唯一原因是_函数运行,则可以导入为init

相关问题