67 lines
2.0 KiB
Go
67 lines
2.0 KiB
Go
package synthetic
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
|
|
"git.ilapage.cn/ila/yovision/Bell/server/app/auth"
|
|
"git.ilapage.cn/ila/yovision/Bell/server/app/event"
|
|
"git.ilapage.cn/ila/yovision/Bell/server/app/rbac"
|
|
)
|
|
|
|
type HTTP struct {
|
|
Service Service
|
|
Auth auth.HTTP
|
|
}
|
|
|
|
func (h HTTP) Register(mux *http.ServeMux) {
|
|
mux.Handle("GET /api/v1/synthetic/fixtures", h.Auth.Require(rbac.SyntheticWrite, http.HandlerFunc(h.fixtures)))
|
|
mux.Handle("POST /api/v1/synthetic/events", h.Auth.Require(rbac.SyntheticWrite, http.HandlerFunc(h.inject)))
|
|
}
|
|
func (h HTTP) fixtures(w http.ResponseWriter, r *http.Request) {
|
|
items, err := h.Service.Fixtures()
|
|
if err != nil {
|
|
writeJSON(w, 500, map[string]string{"error": "读取夹具失败"})
|
|
return
|
|
}
|
|
type summary struct {
|
|
Name string `json:"name"`
|
|
Label string `json:"label"`
|
|
ExpectedFailure bool `json:"expected_failure"`
|
|
}
|
|
result := make([]summary, 0, len(items))
|
|
for _, item := range items {
|
|
result = append(result, summary{Name: item.Name, Label: item.Label, ExpectedFailure: item.ValidationError != ""})
|
|
}
|
|
writeJSON(w, 200, map[string]any{"items": result})
|
|
}
|
|
func (h HTTP) inject(w http.ResponseWriter, r *http.Request) {
|
|
var input Input
|
|
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&input); err != nil {
|
|
writeJSON(w, 400, map[string]string{"error": "请求格式无效"})
|
|
return
|
|
}
|
|
result, err := h.Service.Inject(r.Context(), input)
|
|
if err != nil {
|
|
status := 500
|
|
if errors.Is(err, ErrFixture) || errors.Is(err, event.ErrInvalid) {
|
|
status = 400
|
|
} else if errors.Is(err, event.ErrConflict) {
|
|
status = 409
|
|
}
|
|
writeJSON(w, status, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
status := 201
|
|
if result.Duplicate {
|
|
status = 200
|
|
}
|
|
writeJSON(w, status, result)
|
|
}
|
|
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)
|
|
}
|