github.com/qjfoidnh/BaiduPCS-Go@v0.0.0-20231011165705-caa18a3765f3/baidupcs/expires/expires.go (about)

     1  package expires
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  	_ "unsafe" // for go:linkname
     7  )
     8  
     9  type (
    10  	Expires interface {
    11  		IsExpires() bool
    12  		GetExpires() time.Time
    13  		SetExpires(e bool)
    14  		fmt.Stringer
    15  	}
    16  
    17  	expires struct {
    18  		expiresAt time.Time
    19  		abort     bool
    20  	}
    21  )
    22  
    23  //go:linkname stripMono time.(*Time).stripMono
    24  func stripMono(t *time.Time)
    25  
    26  // StripMono strip monotonic clocks
    27  func StripMono(t *time.Time) {
    28  	stripMono(t)
    29  }
    30  
    31  func NewExpires(dur time.Duration) Expires {
    32  	t := time.Now().Add(dur)
    33  	StripMono(&t)
    34  	return &expires{
    35  		expiresAt: t,
    36  	}
    37  }
    38  
    39  func NewExpiresAt(at time.Time) Expires {
    40  	StripMono(&at)
    41  	return &expires{
    42  		expiresAt: at,
    43  	}
    44  }
    45  
    46  func (ep *expires) GetExpires() time.Time {
    47  	return ep.expiresAt
    48  }
    49  
    50  func (ep *expires) SetExpires(e bool) {
    51  	ep.abort = e
    52  }
    53  
    54  func (ep *expires) IsExpires() bool {
    55  	return ep.abort || time.Now().After(ep.expiresAt)
    56  }
    57  
    58  func (ep *expires) String() string {
    59  	return fmt.Sprintf("expires at: %s, abort: %t", ep.expiresAt, ep.abort)
    60  }