func (mr *MsgRepository) GetMsgs(userID types.ID, sinceID types.ID, size int) ([]*domain.Msg, error) { log.Debug(userID, sinceID, size) tableName := getUserMsgTable(userID) msgs := make([]*domain.Msg, 0, size) var seqID int64 var err error defer func() { if err != nil { msgs = msgs[0:0] log.Error("[GetUserMsgs]", tableName, sinceID, size, err) } if err == sql.ErrNoRows { err = nil } }() if sinceID > 0 { err = mr.db.QueryRow("select id from "+tableName+" where msg_id=?", sinceID).Scan(&seqID) if err == sql.ErrNoRows { err = mr.db.QueryRow("select id from "+tableName+" where msg_id>? order by id limit 1", sinceID).Scan(&seqID) } if err != nil { return nil, err } } var rows *sql.Rows query := "select " + msgFields + " from " + tableName + " where user_id=? and id>? order by id limit ?" rows, err = mr.db.Query(query, userID, seqID, size) if err != nil { return nil, err } defer rows.Close() var cdata, atData []byte for rows.Next() { msg := &domain.Msg{} err = rows.Scan(&msg.ID, &msg.LocalID, &msg.SenderID, &msg.ReceiverID, &cdata, &msg.CreatedAt, &atData) if err != nil { break } gjson.Unmarshal(cdata, &msg.Content) if len(atData) > 0 { gjson.Unmarshal(atData, &msg.AtUserIDs) } msgs = append(msgs, msg) } if len(msgs) == 0 { log.Debug(query) } return msgs, nil }
func Serve(name string, addr string, h RequestHandlerFunc) { creator := namedServerCreators[name] if creator == nil { panic("no server registered for name " + name) } s := creator() log.Info("start serving at", addr) conns := newUserConns() addrConns[addr] = conns err := s.Serve(addr, func(c Conn) { log.Info("new conn", c) for { req, err := c.Receive(time.Minute * 5) if err != nil { log.Error(getUserID(c), err) break } if req != nil { log.Debug("recv:", req) ctx := &ConnContext{} ctx.conns = conns ctx.conn = c h(ctx, req) } } conns.remove(c) c.Close() log.Info("close conn", c) }) if err != nil { panic(err) } }