Mercurial > gemma
changeset 5324:348d91848278 extented-report
Added and endpoint GET /api/data/reports to list the available report templates.
author | Sascha L. Teichmann <sascha.teichmann@intevation.de> |
---|---|
date | Sun, 30 May 2021 01:26:36 +0200 |
parents | eec88a166251 |
children | 313bf3f3a8b1 |
files | pkg/controllers/report.go pkg/controllers/routes.go |
diffstat | 2 files changed, 77 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- a/pkg/controllers/report.go Sat May 29 17:19:03 2021 +0200 +++ b/pkg/controllers/report.go Sun May 30 01:26:36 2021 +0200 @@ -19,15 +19,86 @@ "net/http" "os" "path/filepath" + "sort" + "strings" "gemma.intevation.de/gemma/pkg/config" "gemma.intevation.de/gemma/pkg/middleware" "gemma.intevation.de/gemma/pkg/xlsx" + mw "gemma.intevation.de/gemma/pkg/middleware" + "github.com/360EntSecGroup-Skylar/excelize/v2" "github.com/gorilla/mux" ) +func listReports(req *http.Request) (jr mw.JSONResult, err error) { + path := config.ReportPath() + if path == "" { + err = mw.JSONError{ + Code: http.StatusNotFound, + Message: http.StatusText(http.StatusNotFound), + } + return + } + + // This would be easier with Go 1.16+. + + dir, err := os.Open(path) + if err != nil { + log.Printf("error: %v\n", err) + err = mw.JSONError{ + Code: http.StatusInternalServerError, + Message: "Listing report templates failed.", + } + return + } + defer dir.Close() + files, err := dir.Readdirnames(-1) + if err != nil { + log.Printf("error: %v\n", err) + err = mw.JSONError{ + Code: http.StatusInternalServerError, + Message: "Listing report templates failed.", + } + return + } + + pairs := map[string]int{} + +all: + for _, file := range files { + var mask int + switch { + case strings.HasSuffix(file, ".xlsx"): + mask = 1 + case strings.HasSuffix(file, ".yaml"): + mask = 2 + default: + continue all + } + basename := filepath.Base(file) + name := strings.TrimSuffix(basename, filepath.Ext(basename)) + pairs[name] |= mask + } + + var reports []string + for name, mask := range pairs { + if mask == 3 { + reports = append(reports, name) + } + } + sort.Strings(reports) + + out := struct { + Reports []string `json:"reports"` + }{ + Reports: reports, + } + jr = mw.JSONResult{Result: out} + return +} + func report(rw http.ResponseWriter, req *http.Request) { path := config.ReportPath()
--- a/pkg/controllers/routes.go Sat May 29 17:19:03 2021 +0200 +++ b/pkg/controllers/routes.go Sun May 30 01:26:36 2021 +0200 @@ -324,6 +324,12 @@ // Handler for reporting + api.Handle("/data/reports", + waterwayAdmin(&mw.JSONHandler{ + Handle: listReports, + NoConn: true, + })).Methods(http.MethodGet) + api.Handle("/data/report/{name:[a-zA-Z0-9_]+}", waterwayAdmin( mw.DBConn(http.HandlerFunc(report)))).Methods(http.MethodGet)