77 lines
2.0 KiB
Go
77 lines
2.0 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"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
|
|
}
|
|
|
|
summaries, err := sqlite.listAll(r.Context())
|
|
if err != nil {
|
|
logger.Error("list flashcards", zap.Error(err))
|
|
http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string][]flashcardSummary{"flashcards": summaries})
|
|
})
|
|
|
|
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)
|
|
}
|