MarketingSystemDataExportTool/server/internal/api/creators.go

78 lines
1.8 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package api
import (
"database/sql"
"fmt"
"net/http"
"strconv"
"strings"
)
type CreatorsAPI struct {
db *sql.DB
}
func CreatorsHandler(db *sql.DB) http.Handler {
api := &CreatorsAPI{db: db}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p := strings.TrimPrefix(r.URL.Path, "/api/creators")
if r.Method == http.MethodGet && p == "" {
api.list(w, r)
return
}
w.WriteHeader(http.StatusNotFound)
})
}
func (a *CreatorsAPI) 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
}
}
// 查询 admin_user 表的 id、real_name、mobile
sqlStr := "SELECT id, COALESCE(real_name, ''), COALESCE(mobile, '') FROM `admin_user` WHERE delete_time = 0"
args := []interface{}{}
if q != "" {
sqlStr += " AND (CAST(id AS CHAR) LIKE ? OR real_name LIKE ? OR mobile LIKE ?)"
like := "%" + q + "%"
args = append(args, like, like, like)
}
sqlStr += " ORDER BY id ASC LIMIT ?"
args = append(args, limit)
rows, err := a.db.Query(sqlStr, 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
var mobile sql.NullString
if err := rows.Scan(&id, &name, &mobile); err != nil {
continue
}
if !id.Valid {
continue
}
n := strings.TrimSpace(name.String)
if n == "" {
n = strconv.FormatInt(id.Int64, 10)
}
m := strings.TrimSpace(mobile.String)
display := fmt.Sprintf("%s%d", n, id.Int64)
item := map[string]interface{}{
"id": id.Int64,
"name": display,
"mobile": m,
}
out = append(out, item)
}
ok(w, r, out)
}