(fetch func() []T, rw http.ResponseWriter, r *http.Request)
| 87 | } |
| 88 | } |
| 89 | func ReturnFetchList[T any](fetch func() []T, rw http.ResponseWriter, r *http.Request) { |
| 90 | query := r.URL.Query() |
| 91 | isYaml := query.Get("format") == "yaml" |
| 92 | isJson := query.Get("format") == "json" |
| 93 | pageSize := query.Get("pageSize") |
| 94 | pageNum := query.Get("pageNum") |
| 95 | data := fetch() |
| 96 | var output any |
| 97 | output = data |
| 98 | if pageSize != "" && pageNum != "" { |
| 99 | pageSizeInt, _ := strconv.Atoi(pageSize) |
| 100 | pageNumInt, _ := strconv.Atoi(pageNum) |
| 101 | if pageSizeInt > 0 && pageNumInt > 0 { |
| 102 | start := (pageNumInt - 1) * pageSizeInt |
| 103 | end := pageNumInt * pageSizeInt |
| 104 | if start > len(data) { |
| 105 | start = len(data) |
| 106 | } |
| 107 | if end > len(data) { |
| 108 | end = len(data) |
| 109 | } |
| 110 | output = map[string]any{ |
| 111 | "total": len(data), |
| 112 | "list": data[start:end], |
| 113 | "pageSize": pageSizeInt, |
| 114 | "pageNum": pageNumInt, |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | rw.Header().Set("Content-Type", Conditoinal(isYaml, "text/yaml", "application/json")) |
| 119 | if isYaml { |
| 120 | if err := yaml.NewEncoder(rw).Encode(output); err != nil { |
| 121 | http.Error(rw, err.Error(), http.StatusInternalServerError) |
| 122 | } |
| 123 | } else if isJson { |
| 124 | if err := json.NewEncoder(rw).Encode(APIResult{ |
| 125 | Code: 0, |
| 126 | Data: output, |
| 127 | Message: "ok", |
| 128 | }); err != nil { |
| 129 | json.NewEncoder(rw).Encode(APIError{ |
| 130 | Code: APIErrorJSONEncode, |
| 131 | Message: err.Error(), |
| 132 | }) |
| 133 | } |
| 134 | } else { |
| 135 | if err := json.NewEncoder(rw).Encode(output); err != nil { |
| 136 | http.Error(rw, err.Error(), http.StatusInternalServerError) |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | func ReturnFetchValue[T any](fetch func() T, rw http.ResponseWriter, r *http.Request) { |
| 141 | query := r.URL.Query() |
| 142 | isYaml := query.Get("format") == "yaml" |
nothing calls this directly
no test coverage detected