From 0440dd11e1e2ab3dc991d3c17500ce66e2f32615 Mon Sep 17 00:00:00 2001 From: NatureFreshMilk Date: Wed, 13 Mar 2019 08:55:59 +0100 Subject: [PATCH] api/areas endpoint and config --- server/app/config.go | 2 ++ server/web/areas.go | 56 ++++++++++++++++++++++++++++++++++++++++++++ server/web/serve.go | 4 ++++ 3 files changed, 62 insertions(+) create mode 100644 server/web/areas.go diff --git a/server/app/config.go b/server/app/config.go index ec771a7..707b73e 100644 --- a/server/app/config.go +++ b/server/app/config.go @@ -30,6 +30,7 @@ type MapBlockAccessorConfig struct { } type MapObjectConfig struct { + Areas bool `json:"areas"` Bones bool `json:"bones"` Protector bool `json:"protector"` XPProtector bool `json:"xpprotector"` @@ -107,6 +108,7 @@ func ParseConfig(filename string) (*Config, error) { } mapobjs := MapObjectConfig{ + Areas: true, Bones: true, Protector: true, XPProtector: true, diff --git a/server/web/areas.go b/server/web/areas.go new file mode 100644 index 0000000..0a08b2d --- /dev/null +++ b/server/web/areas.go @@ -0,0 +1,56 @@ +package web + +import ( + "encoding/json" + "mapserver/app" + "mapserver/areasparser" + "net/http" + + "os" + "sync" + "time" +) + +type AreasHandler struct { + ctx *app.App + cache []*areasparser.Area + lasttime int64 +} + +var mutex = &sync.Mutex{} + +const AREAS_FILENAME = "areas.dat" + +func (h *AreasHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) { + info, err := os.Stat(AREAS_FILENAME) + if info == nil || err != nil { + // no areas file + resp.Header().Add("content-type", "application/json") + resp.Write([]byte("[]")) + return + } + + now := time.Now().Unix() + diff := now - h.lasttime + + if diff > 5 { + mutex.Lock() + + h.lasttime = now + areas, err := areasparser.ParseFile(AREAS_FILENAME) + + if err != nil { + resp.WriteHeader(500) + resp.Write([]byte(err.Error())) + return + } + + h.cache = areas + + mutex.Unlock() + } + + resp.Header().Add("content-type", "application/json") + json.NewEncoder(resp).Encode(h.cache) + +} diff --git a/server/web/serve.go b/server/web/serve.go index c28043a..88c7dd0 100644 --- a/server/web/serve.go +++ b/server/web/serve.go @@ -28,6 +28,10 @@ func Serve(ctx *app.App) { mux.Handle("/api/minetest", &Minetest{ctx: ctx}) mux.Handle("/api/mapobjects/", &MapObjects{ctx: ctx}) + if ctx.Config.MapObjects.Areas { + mux.Handle("/api/areas", &AreasHandler{ctx: ctx}) + } + if ctx.Config.EnablePrometheus { mux.Handle("/metrics", promhttp.Handler()) }