dongwuwei0718 2015-05-21 12:40
浏览 422
已采纳

在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()
}
  • 写回答

1条回答 默认 最新

  • doz59484 2015-05-21 16:02
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器