github.com/ulule/limiter/v3@v3.11.3-0.20230613131926-4cb9c1da4633/rate.go (about)

     1  package limiter
     2  
     3  import (
     4  	"strconv"
     5  	"strings"
     6  	"time"
     7  
     8  	"github.com/pkg/errors"
     9  )
    10  
    11  // Rate is the rate.
    12  type Rate struct {
    13  	Formatted string
    14  	Period    time.Duration
    15  	Limit     int64
    16  }
    17  
    18  // NewRateFromFormatted returns the rate from the formatted version.
    19  func NewRateFromFormatted(formatted string) (Rate, error) {
    20  	rate := Rate{}
    21  
    22  	values := strings.Split(formatted, "-")
    23  	if len(values) != 2 {
    24  		return rate, errors.Errorf("incorrect format '%s'", formatted)
    25  	}
    26  
    27  	periods := map[string]time.Duration{
    28  		"S": time.Second,    // Second
    29  		"M": time.Minute,    // Minute
    30  		"H": time.Hour,      // Hour
    31  		"D": time.Hour * 24, // Day
    32  	}
    33  
    34  	limit, period := values[0], strings.ToUpper(values[1])
    35  
    36  	p, ok := periods[period]
    37  	if !ok {
    38  		return rate, errors.Errorf("incorrect period '%s'", period)
    39  	}
    40  
    41  	l, err := strconv.ParseInt(limit, 10, 64)
    42  	if err != nil {
    43  		return rate, errors.Errorf("incorrect limit '%s'", limit)
    44  	}
    45  
    46  	rate = Rate{
    47  		Formatted: formatted,
    48  		Period:    p,
    49  		Limit:     l,
    50  	}
    51  
    52  	return rate, nil
    53  }