MarketingSystemDataTool/server/internal/api/ymt_users.go

58 lines
1.6 KiB
Go

package api
import (
"database/sql"
"net/http"
"strconv"
"strings"
)
type YMTUsersAPI struct {
ymt *sql.DB
}
func YMTUsersHandler(ymt *sql.DB) http.Handler {
api := &YMTUsersAPI{ymt: ymt}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p := strings.TrimPrefix(r.URL.Path, "/api/ymt/users")
if r.Method == http.MethodGet && p == "" {
api.list(w, r)
return
}
w.WriteHeader(http.StatusNotFound)
})
}
func (a *YMTUsersAPI) list(w http.ResponseWriter, r *http.Request) {
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 }
}
sql1 := "SELECT DISTINCT user_id, COALESCE(user_name, '') AS name FROM activity WHERE user_id IS NOT NULL"
args := []interface{}{}
if q != "" {
sql1 += " AND (CAST(user_id AS CHAR) LIKE ? OR user_name LIKE ?)"
like := "%" + q + "%"
args = append(args, like, like)
}
sql1 += " ORDER BY user_id ASC LIMIT ?"
args = append(args, limit)
rows, err := a.ymt.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 }
out = append(out, map[string]interface{}{"id": id.Int64, "name": name.String})
}
ok(w, r, out)
}