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.

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

报告相同问题?

悬赏问题

  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题