53 lines
1.5 KiB
Go
53 lines
1.5 KiB
Go
package event
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"git.ilapage.cn/ila/yovision/Bell/server/app/auth"
|
|
"git.ilapage.cn/ila/yovision/Bell/server/app/rbac"
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
type HTTP struct {
|
|
Service Service
|
|
Auth auth.HTTP
|
|
}
|
|
|
|
func (h HTTP) Register(mux *http.ServeMux) {
|
|
mux.Handle("GET /api/v1/events", h.Auth.Require(rbac.EventsRead, http.HandlerFunc(h.list)))
|
|
mux.Handle("GET /api/v1/events/{id}", h.Auth.Require(rbac.EventsRead, http.HandlerFunc(h.get)))
|
|
}
|
|
func (h HTTP) list(w http.ResponseWriter, r *http.Request) {
|
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
|
items, err := h.Service.List(r.Context(), limit, r.URL.Query().Get("before"))
|
|
if err != nil {
|
|
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "读取事件失败"})
|
|
return
|
|
}
|
|
next := ""
|
|
if len(items) > 0 {
|
|
next = items[len(items)-1].ID
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"items": items, "next": next})
|
|
}
|
|
func (h HTTP) get(w http.ResponseWriter, r *http.Request) {
|
|
item, err := h.Service.Get(r.Context(), r.PathValue("id"))
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
writeJSON(w, http.StatusNotFound, map[string]string{"error": "事件不存在"})
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "读取事件失败"})
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, item)
|
|
}
|
|
func writeJSON(w http.ResponseWriter, status int, value any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(value)
|
|
}
|