-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add /api/list endpoint to list files/pages as JSON
- Loading branch information
Showing
2 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters