github.com/predbdotovh/pre-api@v0.0.0-20211230223408-096f265fde6a/api.go (about) 1 package main 2 3 import ( 4 "encoding/json" 5 "net/http" 6 "time" 7 ) 8 9 type apiResponse struct { 10 Status string `json:"status"` 11 Message string `json:"message"` 12 Data interface{} `json:"data"` 13 } 14 15 type apiRowData struct { 16 RowCount int `json:"rowCount"` 17 Rows []preRow `json:"rows"` 18 Offset int `json:"offset"` 19 ReqCount int `json:"reqCount"` 20 Total int `json:"total"` 21 Time float64 `json:"time"` 22 } 23 24 type apiStatsData struct { 25 Total int `json:"total"` 26 Date time.Time `json:"date"` 27 Time float64 `json:"time"` 28 } 29 30 type apiTeamsData struct { 31 RowCount int `json:"rowCount"` 32 Rows []teamRow `json:"rows"` 33 Offset int `json:"offset"` 34 ReqCount int `json:"reqCount"` 35 Total int `json:"total"` 36 Time float64 `json:"time"` 37 } 38 39 const indent = " " 40 41 func apiSuccess(w http.ResponseWriter, o interface{}) error { 42 return apiSend(w, apiResponse{"success", "", o}) 43 } 44 45 func apiFail(w http.ResponseWriter, o interface{}) error { 46 return apiSend(w, apiResponse{"error", "", o}) 47 } 48 49 func apiErr(w http.ResponseWriter, err error) error { 50 return apiSend(w, apiResponse{"error", err.Error(), nil}) 51 } 52 53 func apiSend(w http.ResponseWriter, o interface{}) error { 54 headers := w.Header() 55 headers.Set("Content-Type", "application/json; charset=utf-8") 56 headers.Set("Access-Control-Allow-Origin", "*") 57 w.WriteHeader(http.StatusOK) 58 59 enc := json.NewEncoder(w) 60 enc.SetIndent("", indent) 61 62 return enc.Encode(o) 63 }