2
0

response.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package httpserver
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. )
  6. // ColumnInfo represents column metadata.
  7. type ColumnInfo struct {
  8. Name string `json:"name"`
  9. Type string `json:"type"`
  10. }
  11. // QueryResponse represents a query response.
  12. type QueryResponse struct {
  13. Columns []ColumnInfo `json:"columns"`
  14. Rows [][]interface{} `json:"rows"`
  15. RowsAffected int64 `json:"rowsAffected"`
  16. LastInsertID int64 `json:"lastInsertId"`
  17. ExecutionTime string `json:"executionTime"`
  18. QueryPlan []string `json:"queryPlan,omitempty"`
  19. }
  20. // ExecuteResult represents a single execution result.
  21. type ExecuteResult struct {
  22. RowsAffected int64 `json:"rowsAffected"`
  23. LastInsertID int64 `json:"lastInsertId"`
  24. }
  25. // ExecuteResponse represents a batch execution response.
  26. type ExecuteResponse struct {
  27. Results []ExecuteResult `json:"results"`
  28. ExecutionTime string `json:"executionTime"`
  29. }
  30. // ErrorResponse represents an error response.
  31. type ErrorResponse struct {
  32. Error ErrorDetail `json:"error"`
  33. }
  34. // ErrorDetail contains error details.
  35. type ErrorDetail struct {
  36. Code string `json:"code"`
  37. Message string `json:"message"`
  38. Details map[string]interface{} `json:"details,omitempty"`
  39. }
  40. // HTTPError represents an HTTP error with custom fields.
  41. type HTTPError struct {
  42. Code string
  43. Message string
  44. Status int
  45. Details map[string]interface{}
  46. }
  47. func (e *HTTPError) Error() string {
  48. return e.Message
  49. }
  50. // writeJSON writes a JSON response.
  51. func writeJSON(w http.ResponseWriter, status int, data interface{}, pretty bool) {
  52. w.Header().Set("Content-Type", "application/json")
  53. w.WriteHeader(status)
  54. encoder := json.NewEncoder(w)
  55. if pretty {
  56. encoder.SetIndent("", " ")
  57. }
  58. encoder.Encode(data)
  59. }
  60. // writeError writes an error response.
  61. func writeError(w http.ResponseWriter, status int, code, message string, details map[string]interface{}) {
  62. resp := ErrorResponse{
  63. Error: ErrorDetail{
  64. Code: code,
  65. Message: message,
  66. Details: details,
  67. },
  68. }
  69. writeJSON(w, status, resp, false)
  70. }