feat: add REST API for flashcards (/api/v1/flashcards/*)
This commit is contained in:
1 parent
f30d34d20a
commit
cd8e872491
3 files changed
+150
No files matched your search
@@ -0,0 +1,82 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func registerAPI(mux *http.ServeMux, sqlite *sqliteStore, logger *zap.Logger) {
|
||||
mux.HandleFunc("/api/v1/flashcards", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
ids, err := sqlite.listAllPublicIDs(r.Context())
|
||||
if err != nil {
|
||||
logger.Error("list flashcards", zap.Error(err))
|
||||
http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
urls := make([]string, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
urls = append(urls, fmt.Sprintf("/api/v1/flashcards/%d", id))
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string][]string{"flashcards": urls})
|
||||
})
|
||||
|
||||
mux.HandleFunc("/api/v1/flashcards/", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
segments := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/v1/flashcards/"), "/")
|
||||
if len(segments) == 0 || segments[0] == "" {
|
||||
http.Error(w, `{"error":"not found"}`, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
publicID, err := strconv.ParseInt(segments[0], 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, `{"error":"invalid id"}`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if len(segments) >= 2 && segments[1] != "" {
|
||||
version, err := strconv.Atoi(segments[1])
|
||||
if err != nil {
|
||||
http.Error(w, `{"error":"invalid version"}`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
e, err := sqlite.getByPublicIDAndVersion(r.Context(), publicID, version)
|
||||
writeEntry(w, e, err)
|
||||
return
|
||||
}
|
||||
|
||||
e, err := sqlite.getLatestByPublicID(r.Context(), publicID)
|
||||
writeEntry(w, e, err)
|
||||
})
|
||||
}
|
||||
|
||||
func writeEntry(w http.ResponseWriter, e *entry, err error) {
|
||||
if err != nil {
|
||||
http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if e == nil {
|
||||
http.Error(w, `{"error":"not found"}`, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(e)
|
||||
}
|
||||
Reference in new issue
Block a user