feat(platform): add vehicle data management console

This commit is contained in:
lingniu
2026-07-03 20:55:54 +08:00
parent 0d8916df47
commit 859bc3e9ee
45 changed files with 6837 additions and 0 deletions

View File

@@ -0,0 +1,46 @@
package httpx
import (
"encoding/json"
"net/http"
"time"
)
type Envelope struct {
Data any `json:"data,omitempty"`
Error *Error `json:"error,omitempty"`
TraceID string `json:"traceId"`
Timestamp int64 `json:"timestamp"`
}
type Error struct {
Code string `json:"code"`
Message string `json:"message"`
Detail string `json:"detail,omitempty"`
}
func WriteOK(w http.ResponseWriter, traceID string, data any) {
writeJSON(w, http.StatusOK, Envelope{
Data: data,
TraceID: traceID,
Timestamp: time.Now().UnixMilli(),
})
}
func WriteError(w http.ResponseWriter, status int, code, message, detail, traceID string) {
writeJSON(w, status, Envelope{
Error: &Error{
Code: code,
Message: message,
Detail: detail,
},
TraceID: traceID,
Timestamp: time.Now().UnixMilli(),
})
}
func writeJSON(w http.ResponseWriter, status int, body Envelope) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(body)
}

View File

@@ -0,0 +1,48 @@
package httpx
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestWriteOKWrapsData(t *testing.T) {
rec := httptest.NewRecorder()
WriteOK(rec, "trace-1", map[string]any{"online": 12})
if rec.Code != http.StatusOK {
t.Fatalf("status = %d", rec.Code)
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["traceId"] != "trace-1" {
t.Fatalf("traceId = %#v", body["traceId"])
}
data := body["data"].(map[string]any)
if data["online"].(float64) != 12 {
t.Fatalf("data = %#v", data)
}
}
func TestWriteErrorWrapsError(t *testing.T) {
rec := httptest.NewRecorder()
WriteError(rec, http.StatusBadRequest, "BAD_QUERY", "查询失败", "vin required", "trace-2")
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d", rec.Code)
}
if got := rec.Body.String(); !containsAll(got, []string{"BAD_QUERY", "查询失败", "vin required", "trace-2"}) {
t.Fatalf("body = %s", got)
}
}
func containsAll(value string, parts []string) bool {
for _, part := range parts {
if !strings.Contains(value, part) {
return false
}
}
return true
}