在Goji中映射所有路线及其http方法

问题描述:

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?

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()
}

我想映射每条路线及其生成的请求类型(GET,POST,PUT等) 像JSON中用于我的静态API的sitemap.xml之类的。 p>

Goji使用函数来创建新路线。 我可以将路径和处理程序存储在地图中。 p>

我的方法将是这样的,除了编译器会给出以下初始化循环错误外,因为 sitemap code> 和 routes code>相互引用(路由图包含应处理自身的处理程序站点图)。 p>

  main.go:18:初始化循环:
 main.go:18路由引用
 main.go:41站点地图引用
 main.go:18 路线
  code>  pre> 
 
 

能否以一种惯用的方式实现? p>

 包main 
 
import(
“ encoding / json” 
“ net / http” 
 
“ github.com/zenazn/goji"
  “ github.com/zenazn/goji/web"
)

var路由= [] Route {
 Route {” Get“,” / index“,hello},
 Route {” Get“,” /  sitemap“,sitemap},
} 
 
type路由结构{
方法字符串`json:”方法“`
模式字符串`json:” pattern“`
处理程序web.HandlerType`json:”-“  `
} 
 
func NewRoute(方法,模式字符串,处理程序web.HandlerType){
切换方法{
 case“ Get”,“ get”:
 goji.DefaultMux.Get(样式,处理程序)\  n case“ Post”,“ post”:
 goji.DefaultMux.Post(pattern,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){
 //错误:Sitemap试图递归地整理自身
响应,_:= json.MarshalIndent(routes,“”,“”)
 //一些错误处理... 
 w。  Write(resp)
} 
 
func main(){
 
表示_,r:=范围路由{
 NewRoute(r.Method,r.Pattern,r.Handler)
} 
 \  n goji.Serve()
} 
  code>  pre> 
  div>

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{"Get", "/index", hello},
        Route{"Get", "/sitemap", 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 (
    "encoding/json"
    "net/http"

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

var routes []Route

func init() {
    // Initialzed in init() to avoid an initialization loop
    // since `routes` refers to `sitemap` refers to `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,
    // … others?
}

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()
}

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.