在外部包中注册Golang gorilla/mux的路由。

huangapple go评论65阅读模式
英文:

Register Golang gorilla/mux routes in external package

问题

在我的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/router.go

package router

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

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

handlers/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...")
}
英文:

In my API I'm going to have a lot of completely separate handlers for each path like "/api/v1/handler_one" and "/api/v1/handler_two". I'm trying to put every handler in it's own package to make it easier to maintain.

I added an example. It's not working since it's not even loading "handlers/handler_one.go". What am I missing?

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/router.go

package router

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

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

handlers/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

得分: 1

你的意思是 handlers/handler_one.go 中的 init 函数没有被执行吗?

这是可以预料的,因为在你贴出的代码中,你没有在任何地方导入该包。

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

如果导入该包的唯一原因是为了执行 init 函数,你可以使用 _ 进行导入。

英文:

> It's not working since it's not even loading "handlers/handler_one.go"

Do you mean that the init function in handlers/handler_one.go is not being executed?

That would be expected since in the code you pasted you are not importing that package anywhere.

Try importing that package in your main.go.

You can import as _ if the only reason for importing it would be for the init function to run.

huangapple
  • 本文由 发表于 2017年6月8日 00:51:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/44418576.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定