Skip to content

Commit

Permalink
Add /api/list endpoint to list files/pages as JSON
Browse files Browse the repository at this point in the history
Issue #54, issue #32
  • Loading branch information
csmith committed Apr 7, 2021
1 parent 2607b71 commit a3daaff
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
47 changes: 47 additions & 0 deletions handlers_api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package main

import (
"encoding/json"
"log"
"net/http"
)

type Lister interface {
ListPages() ([]string, error)
ListFiles() ([]File, error)
}

func ApiListHandler(l Lister) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var res []string

if r.FormValue("type") == "file" {
files, err := l.ListFiles()
if err != nil {
log.Printf("Failed to list files: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
for i := range files {
res = append(res, files[i].Name)
}
} else {
pages, err := l.ListPages()
if err != nil {
log.Printf("Failed to list pages: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
res = pages
}

b, err := json.Marshal(res)
if err != nil {
log.Printf("Failed to marshal list contents: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
}

_, _ = w.Write(b)
}
}
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ func main() {
wikiRouter.PathPrefix("/delete/").Handler(write(DeletePageHandler(gitBackend))).Methods(http.MethodPost)
wikiRouter.PathPrefix("/rename/").Handler(write(RenamePageConfirmHandler(gitBackend, templates))).Methods(http.MethodGet)
wikiRouter.PathPrefix("/rename/").Handler(write(RenamePageHandler(gitBackend))).Methods(http.MethodPost)
wikiRouter.Path("/api/list").Handler(read(ApiListHandler(gitBackend))).Methods(http.MethodGet)
wikiRouter.Path("/wiki/account").Handler(auth(AccountHandler(templates))).Methods(http.MethodGet)
wikiRouter.Path("/wiki/account").Handler(auth(ModifyAccountHandler(userManager))).Methods(http.MethodPost)
wikiRouter.Path("/wiki/index").Handler(read(ListPagesHandler(templates, gitBackend))).Methods(http.MethodGet)
Expand Down

0 comments on commit a3daaff

Please sign in to comment.