git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/mailgun/rfc2822.go (about)

     1  package mailgun
     2  
     3  import (
     4  	"strconv"
     5  	"strings"
     6  	"time"
     7  )
     8  
     9  // Mailgun uses RFC2822 format for timestamps everywhere ('Thu, 13 Oct 2011 18:02:00 GMT'), but
    10  // by default Go's JSON package uses another format when decoding/encoding timestamps.
    11  type RFC2822Time time.Time
    12  
    13  func NewRFC2822Time(str string) (RFC2822Time, error) {
    14  	t, err := time.Parse(time.RFC1123, str)
    15  	if err != nil {
    16  		return RFC2822Time{}, err
    17  	}
    18  	return RFC2822Time(t), nil
    19  }
    20  
    21  func (t RFC2822Time) Unix() int64 {
    22  	return time.Time(t).Unix()
    23  }
    24  
    25  func (t RFC2822Time) IsZero() bool {
    26  	return time.Time(t).IsZero()
    27  }
    28  
    29  func (t RFC2822Time) MarshalJSON() ([]byte, error) {
    30  	return []byte(strconv.Quote(time.Time(t).Format(time.RFC1123))), nil
    31  }
    32  
    33  func (t *RFC2822Time) UnmarshalJSON(s []byte) error {
    34  	q, err := strconv.Unquote(string(s))
    35  	if err != nil {
    36  		return err
    37  	}
    38  	if *(*time.Time)(t), err = time.Parse(time.RFC1123, q); err != nil {
    39  		if strings.Contains(err.Error(), "extra text") {
    40  			if *(*time.Time)(t), err = time.Parse(time.RFC1123Z, q); err != nil {
    41  				return err
    42  			}
    43  			return nil
    44  		}
    45  		return err
    46  	}
    47  	return nil
    48  }
    49  
    50  func (t RFC2822Time) String() string {
    51  	return time.Time(t).Format(time.RFC1123)
    52  }