package response import ( "encoding/json" "net/http" "net/http/httptest" "testing" ) func TestJSON(t *testing.T) { w := httptest.NewRecorder() data := map[string]string{"key": "value"} JSON(w, http.StatusOK, data) if w.Code != http.StatusOK { t.Errorf("status = %d, want %d", w.Code, http.StatusOK) } if ct := w.Header().Get("Content-Type"); ct != "application/json" { t.Errorf("Content-Type = %s, want application/json", ct) } var resp APIResponse if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { t.Fatalf("failed to unmarshal: %v", err) } if resp.Code != 0 { t.Errorf("code = %d, want 0", resp.Code) } if resp.Message != "success" { t.Errorf("message = %s, want success", resp.Message) } } func TestBadRequest(t *testing.T) { w := httptest.NewRecorder() BadRequest(w, "参数错误") if w.Code != http.StatusBadRequest { t.Errorf("status = %d, want %d", w.Code, http.StatusBadRequest) } } func TestUnauthorized(t *testing.T) { w := httptest.NewRecorder() Unauthorized(w, "未登录") if w.Code != http.StatusUnauthorized { t.Errorf("status = %d, want %d", w.Code, http.StatusUnauthorized) } } func TestForbidden(t *testing.T) { w := httptest.NewRecorder() Forbidden(w, "无权限") if w.Code != http.StatusForbidden { t.Errorf("status = %d, want %d", w.Code, http.StatusForbidden) } } func TestNotFound(t *testing.T) { w := httptest.NewRecorder() NotFound(w, "资源不存在") if w.Code != http.StatusNotFound { t.Errorf("status = %d, want %d", w.Code, http.StatusNotFound) } } func TestInternalError(t *testing.T) { w := httptest.NewRecorder() InternalError(w, "内部错误") if w.Code != http.StatusInternalServerError { t.Errorf("status = %d, want %d", w.Code, http.StatusInternalServerError) } } func TestTooManyRequests(t *testing.T) { w := httptest.NewRecorder() TooManyRequests(w, "过于频繁") if w.Code != http.StatusTooManyRequests { t.Errorf("status = %d, want %d", w.Code, http.StatusTooManyRequests) } }