package server import ( "fmt" "local/dndex/config" "local/dndex/server/auth" "local/dndex/storage" "local/router" "net/http" "path" "strings" ) type REST struct { port int router *router.Router g storage.RateLimitedGraph } func Listen(g storage.RateLimitedGraph) error { rest, err := NewREST(g) if err != nil { return err } return http.ListenAndServe(fmt.Sprintf(":%d", rest.port), rest.router) } func NewREST(g storage.RateLimitedGraph) (*REST, error) { rest := &REST{ g: g, port: config.New().Port, router: router.New(), } param := router.Wildcard params := router.Wildcard + router.Wildcard paths := map[string]http.HandlerFunc{ fmt.Sprintf("version"): rest.version, fmt.Sprintf("%s/%s", config.New().FilePrefix, params): rest.files, fmt.Sprintf("users/%s", param): rest.users, fmt.Sprintf("entities/%s", params): rest.entities, fmt.Sprintf("dump"): rest.dump, } for urlpath, foo := range paths { bar := foo bar = rest.shift(bar) bar = rest.scoped(bar) switch strings.Split(urlpath, "/")[0] { case "users": case "version": default: bar = rest.auth(bar) } bar = rest.defend(bar) bar = rest.delay(bar) bar = rest.deprefix(bar) routerpath := path.Join("/", config.New().APIPrefix, urlpath) if err := rest.router.Add(routerpath, bar); err != nil { return nil, err } } bar := rest.static bar = rest.defend(bar) bar = rest.delay(bar) if err := rest.router.Add(params, bar); err != nil { return nil, err } return rest, nil } func (rest *REST) scope(r *http.Request) auth.Scope { return auth.GetScope(r, rest.g) }