github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/znet/limiter/statistics.go (about)

     1  package limiter
     2  
     3  import (
     4  	"fmt"
     5  	"sort"
     6  
     7  	"github.com/sohaha/zlsgo/znet"
     8  )
     9  
    10  // Remaining Remaining visits
    11  func (r *Rule) Remaining(key interface{}) []int {
    12  	arr := make([]int, 0, len(r.rules))
    13  	for i := range r.rules {
    14  		arr = append(arr, r.rules[i].remainingVisits(key))
    15  	}
    16  	return arr
    17  }
    18  
    19  // RemainingVisitsByIP Remaining Visits IP
    20  func (r *Rule) RemainingVisitsByIP(ip string) []int {
    21  	ipUint, _ := znet.IPToLong(ip)
    22  	if ipUint == 0 {
    23  		return []int{}
    24  	}
    25  	return r.Remaining(ipUint)
    26  }
    27  
    28  // GetOnline Get all current online users
    29  func (r *Rule) GetOnline() []string {
    30  	var insertIgnoreString = func(s []string, v string) []string {
    31  		for _, val := range s {
    32  			if val == v {
    33  				return s
    34  			}
    35  		}
    36  		s = append(s, v)
    37  		return s
    38  	}
    39  	var users []string
    40  	for i := range r.rules {
    41  		f := func(k, v interface{}) bool {
    42  			var user string
    43  			switch v := k.(type) {
    44  			case uint:
    45  				user, _ = znet.LongToIP(v)
    46  			default:
    47  				user = fmt.Sprint(k)
    48  			}
    49  			users = insertIgnoreString(users, user)
    50  			return true
    51  		}
    52  		r.rules[i].usedRecordsIndex.Range(f)
    53  	}
    54  	sort.Strings(users)
    55  	return users
    56  }