package api import ( "database/sql" "net/http" "strconv" "strings" ) type ResellersAPI struct { marketing *sql.DB } func ResellersHandler(marketing *sql.DB) http.Handler { api := &ResellersAPI{marketing: marketing} return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { p := strings.TrimPrefix(r.URL.Path, "/api/resellers") if r.Method == http.MethodGet && p == "" { api.list(w, r) return } w.WriteHeader(http.StatusNotFound) }) } func (a *ResellersAPI) list(w http.ResponseWriter, r *http.Request) { creatorsParam := r.URL.Query().Get("creator") q := r.URL.Query().Get("q") limitStr := r.URL.Query().Get("limit") limit := 2000 if limitStr != "" { if n, err := strconv.Atoi(limitStr); err == nil && n > 0 && n <= 10000 { limit = n } } creators := []string{} for _, s := range strings.Split(creatorsParam, ",") { s = strings.TrimSpace(s) if s != "" { creators = append(creators, s) } } if len(creators) == 0 { ok(w, r, []map[string]interface{}{}) return } ph := strings.Repeat("?,", len(creators)) ph = strings.TrimSuffix(ph, ",") sql1 := "SELECT DISTINCT reseller_id, COALESCE(reseller_name,'') AS name FROM plan WHERE reseller_id IS NOT NULL AND creator IN (" + ph + ")" args := []interface{}{} for _, c := range creators { args = append(args, c) } if q != "" { sql1 += " AND (CAST(reseller_id AS CHAR) LIKE ? OR reseller_name LIKE ?)" like := "%" + q + "%" args = append(args, like, like) } sql1 += " ORDER BY reseller_id ASC LIMIT ?" args = append(args, limit) rows, err := a.marketing.Query(sql1, args...) if err != nil { fail(w, r, http.StatusInternalServerError, err.Error()) return } defer rows.Close() out := []map[string]interface{}{} for rows.Next() { var id sql.NullInt64 var name sql.NullString if err := rows.Scan(&id, &name); err != nil { continue } if !id.Valid { continue } m := map[string]interface{}{"id": id.Int64, "name": name.String} out = append(out, m) } ok(w, r, out) }