0

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()
}
user3147268
  • 1,814
  • 7
  • 26
  • 39
  • Usually I do so but I don't wanted to keep the example as simple as possible. Thanks for the tip with `init()` – user3147268 May 21 '15 at 16:07
  • wrt errors, that's fine; it's just I see that too often in "real" code, probably from niave people cut-n-pasting, which is why I sometimes point it out and I prefer to simplify examples to no less than a comment about checking the error (i.e. `// … handle error …` or somesuch) – Dave C May 21 '15 at 16:17
  • I added an annotion. – user3147268 May 21 '15 at 16:22
  • Would you stick with the switch-case approach? – user3147268 May 21 '15 at 16:23
  • I don't know/use `goji` so I'm unfamilar with it. However, your two cases call functions with identical signatures so perhaps you could consider using either an interface or a `type x func(string, web.Handler)`, either as the argument or as a map entry (or a field of `Route`) or whatever. As this may be getting off-topic from the question or too chatty we could take this to [chat] if you liked. – Dave C May 21 '15 at 16:35

1 Answers1

1

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.

Dave C
  • 7,729
  • 4
  • 49
  • 65