在Goji中映射所有路由及其HTTP方法。

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

Mapping all routes and its http methods in Goji

问题

我想为我的RESTful API将每个路由及其请求类型(GET、POST、PUT等)映射到类似于JSON格式的sitemap.xml,可以使用Goji的函数来创建新的路由。可以将路径和处理程序存储在一个映射中。

我的方法类似于下面的代码,但是编译器会报初始化循环错误,因为sitemaproutes相互引用(routemap包含应该自己进行编组的处理程序sitemap)。

package main

import (
	"encoding/json"
	"net/http"

	"github.com/zenazn/goji"
	"github.com/zenazn/goji/web"
)

var routes = []Route{
	Route{"Get", "/index", hello},
	Route{"Get", "/sitemap", sitemap},
}

type Route struct {
	Method  string          `json:"method"`
	Pattern string          `json:"pattern"`
	Handler web.HandlerType `json:"-"`
}

func NewRoute(method, pattern string, handler web.HandlerType) {
	switch method {
	case "Get", "get":
		goji.DefaultMux.Get(pattern, handler)
	case "Post", "post":
		goji.DefaultMux.Post(pattern, handler)
		// and so on...
	}

}

func hello(c web.C, w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello world"))
}

func sitemap(c web.C, w http.ResponseWriter, r *http.Request) {
	// BUG: sitemap tries to marshall itself recursively
	resp, _ := json.MarshalIndent(routes, "", "    ")
	// some error handling...
	w.Write(resp)
}

func main() {

	for _, r := range routes {
		NewRoute(r.Method, r.Pattern, r.Handler)
	}

	goji.Serve()
}

有没有更符合惯用方式的实现方法呢?

英文:

I would like to map each route and it's request type (GET, POST, PUT, ...) to generate something like a sitemap.xml in JSON for my restful API.

Goji uses functions to create a new route. I could store the paths and handlers in a map.

My approach would be something like this, except that the compiler gives the following initialization loop error, because sitemap and routes refer to each other (the routemap contains the handler sitemap that should marhsall itself).

main.go:18: initialization loop:
	main.go:18 routes refers to
	main.go:41 sitemap refers to
	main.go:18 routes

Can this be achieved in a more idiomatic way?

<!-- language: go-lang -->

package main

import (
	&quot;encoding/json&quot;
	&quot;net/http&quot;

	&quot;github.com/zenazn/goji&quot;
	&quot;github.com/zenazn/goji/web&quot;
)

var routes = []Route{
	Route{&quot;Get&quot;, &quot;/index&quot;, hello},
	Route{&quot;Get&quot;, &quot;/sitemap&quot;, sitemap},
}

type Route struct {
	Method  string          `json:&quot;method&quot;`
	Pattern string          `json:&quot;pattern&quot;`
	Handler web.HandlerType `json:&quot;-&quot;`
}

func NewRoute(method, pattern string, handler web.HandlerType) {
	switch method {
	case &quot;Get&quot;, &quot;get&quot;:
		goji.DefaultMux.Get(pattern, handler)
	case &quot;Post&quot;, &quot;post&quot;:
		goji.DefaultMux.Post(pattern, handler)
		// and so on...
	}

}

func hello(c web.C, w http.ResponseWriter, r *http.Request) {
	w.Write([]byte(&quot;Hello world&quot;))
}

func sitemap(c web.C, w http.ResponseWriter, r *http.Request) {
    // BUG: sitemap tries to marshall itself recursively
	resp, _ := json.MarshalIndent(routes, &quot;&quot;, &quot;    &quot;)
// some error handling...
	w.Write(resp)
}

func main() {

	for _, r := range routes {
		NewRoute(r.Method, r.Pattern, r.Handler)
	}

	goji.Serve()
}

答案1

得分: 1

避免初始化循环的最简单方法是通过延迟其中一个初始化来打破循环。

例如:

var routes []Route

func init() {
    routes = []Route{
        Route{"Get", "/index", hello},
        Route{"Get", "/sitemap", sitemap},
    }
}

通过这个改变,你的代码可以编译通过。

[在聊天记录之后进行编辑:]

下面是一个完整的、可运行的示例,还回答了你关于switch的问题:

package main

import (
    "encoding/json"
    "net/http"

    "github.com/zenazn/goji"
    "github.com/zenazn/goji/web"
)

var routes []Route

func init() {
    // 在init()中初始化,以避免初始化循环
    // 因为`routes`引用了`sitemap`,而`sitemap`又引用了`routes`
    routes = []Route{
        Route{"Get", "/index", hello},
        Route{"Get", "/sitemap", sitemap},
        //Route{"Post", "/somewhereElse", postHandlerExample},
    }
}

type Route struct {
    Method  string          `json:"method"`
    Pattern string          `json:"pattern"`
    Handler web.HandlerType `json:"-"`
}

var methods = map[string]func(web.PatternType, web.HandlerType){
    "Get":  goji.Get,
    "Post": goji.Post,
    // … 其他方法?
}

func (r Route) Add() {
    //log.Println("adding", r)
    methods[r.Method](r.Pattern, r.Handler)
}

func hello(c web.C, w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello world"))
}

func sitemap(c web.C, w http.ResponseWriter, r *http.Request) {
    resp, err := json.MarshalIndent(routes, "", "    ")
    if err != nil {
        http.Error(w, "Can't generate response properly.", 500)
        return
    }

    w.Write(resp)
}

func main() {
    for _, r := range routes {
        r.Add()
    }
    goji.Serve()
}

可以在gist中找到完整的代码。

需要注意的是,像你之前写的switch语句并没有问题,在这种情况下,如果只有两种方法,使用map可能有点过度设计。之前的示例版本没有使用map,而是明确指定了函数和方法名(它们应该匹配)。

此版本还没有检查无效的方法名(如果routes始终是硬编码且在运行时不会更改,这是合理的)。如果需要的话,可以很容易地执行fn, ok := methods[r.Method],并在!ok时执行其他操作。

英文:

The easiest way to avoid the initialization loop is to break the loop by delaying one of the initializations.

E.g.:

var routes []Route
func init() {
routes = []Route{
Route{&quot;Get&quot;, &quot;/index&quot;, hello},
Route{&quot;Get&quot;, &quot;/sitemap&quot;, sitemap},
}
}

With this change your code compiles.

[Edit after chat:]

A fully edited and runnable example that also addresses your question about the switch follows:

package main
import (
&quot;encoding/json&quot;
&quot;net/http&quot;
&quot;github.com/zenazn/goji&quot;
&quot;github.com/zenazn/goji/web&quot;
)
var routes []Route
func init() {
// Initialzed in init() to avoid an initialization loop
// since `routes` refers to `sitemap` refers to `routes`.
routes = []Route{
Route{&quot;Get&quot;, &quot;/index&quot;, hello},
Route{&quot;Get&quot;, &quot;/sitemap&quot;, sitemap},
//Route{&quot;Post&quot;, &quot;/somewhereElse&quot;, postHandlerExample},
}
}
type Route struct {
Method  string          `json:&quot;method&quot;`
Pattern string          `json:&quot;pattern&quot;`
Handler web.HandlerType `json:&quot;-&quot;`
}
var methods = map[string]func(web.PatternType, web.HandlerType){
&quot;Get&quot;:  goji.Get,
&quot;Post&quot;: goji.Post,
// … others?
}
func (r Route) Add() {
//log.Println(&quot;adding&quot;, r)
methods[r.Method](r.Pattern, r.Handler)
}
func hello(c web.C, w http.ResponseWriter, r *http.Request) {
w.Write([]byte(&quot;Hello world&quot;))
}
func sitemap(c web.C, w http.ResponseWriter, r *http.Request) {
resp, err := json.MarshalIndent(routes, &quot;&quot;, &quot;    &quot;)
if err != nil {
http.Error(w, &quot;Can&#39;t generate response properly.&quot;, 500)
return
}
w.Write(resp)
}
func main() {
for _, r := range routes {
r.Add()
}
goji.Serve()
}

Available as a gist.

I'll note there is nothing wrong with a switch like you had it,
and in this case if there are only two methods a map may be overkill.
A previous version of the example
didn't use a map and explicitly specified both the function and method name (which were expected to match).

Also this version doesn't check for invalid method names (which if routes is always hard coded and never changed at runtime is reasonable). It would be straight forward to do fn, ok := methods[r.Method] and do something else if/when !ok if desired.

huangapple
  • 本文由 发表于 2015年5月21日 20:40:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/30374089.html
匿名

发表评论

匿名网友

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

确定