dndex/server/rest.go

64 lines
1.3 KiB
Go

package server
import (
"fmt"
"local/dndex/config"
"local/dndex/server/auth"
"local/dndex/storage"
"local/router"
"net/http"
"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,
}
for path, foo := range paths {
bar := foo
bar = rest.shift(bar)
bar = rest.scoped(bar)
if !strings.HasPrefix(path, "users/") && path != "version" {
bar = rest.auth(bar)
}
bar = rest.defend(bar)
bar = rest.delay(bar)
if err := rest.router.Add(path, bar); err != nil {
return nil, err
}
}
return rest, nil
}
func (rest *REST) scope(r *http.Request) auth.Scope {
return auth.GetScope(r, rest.g)
}