diff --git a/github/github.go b/github/github.go index 6b37f082cf6..a24d39dee4e 100644 --- a/github/github.go +++ b/github/github.go @@ -571,7 +571,8 @@ type Response struct { // propagate to Response. Rate Rate - // token's expiration date + // token's expiration date. Timestamp is 0001-01-01 when token doesn't expire. + // So it is valid for TokenExpiration.Equal(Timestamp{}) or TokenExpiration.Time.After(time.Now()) TokenExpiration Timestamp } @@ -672,14 +673,19 @@ func parseRate(r *http.Response) Rate { } // parseTokenExpiration parses the TokenExpiration related headers. +// Returns 0001-01-01 if the header is not defined or could not be parsed. func parseTokenExpiration(r *http.Response) Timestamp { - var exp Timestamp if v := r.Header.Get(headerTokenExpiration); v != "" { - if t, err := time.Parse("2006-01-02 03:04:05 MST", v); err == nil { - exp = Timestamp{t.Local()} + if t, err := time.Parse("2006-01-02 15:04:05 MST", v); err == nil { + return Timestamp{t.Local()} + } + // Some tokens include the timezone offset instead of the timezone. + // https://github.com/google/go-github/issues/2649 + if t, err := time.Parse("2006-01-02 15:04:05 -0700", v); err == nil { + return Timestamp{t.Local()} } } - return exp + return Timestamp{} // 0001-01-01 00:00:00 } type requestContext uint8 diff --git a/github/github_test.go b/github/github_test.go index 7342e2dfd79..0c969404341 100644 --- a/github/github_test.go +++ b/github/github_test.go @@ -2860,6 +2860,16 @@ func TestParseTokenExpiration(t *testing.T) { header: "2021-09-03 02:34:04 UTC", want: Timestamp{time.Date(2021, time.September, 3, 2, 34, 4, 0, time.UTC)}, }, + { + header: "2021-09-03 14:34:04 UTC", + want: Timestamp{time.Date(2021, time.September, 3, 14, 34, 4, 0, time.UTC)}, + }, + // Some tokens include the timezone offset instead of the timezone. + // https://github.com/google/go-github/issues/2649 + { + header: "2023-04-26 20:23:26 +0200", + want: Timestamp{time.Date(2023, time.April, 26, 18, 23, 26, 0, time.UTC)}, + }, } for _, tt := range tests { @@ -2871,7 +2881,7 @@ func TestParseTokenExpiration(t *testing.T) { res.Header.Set(headerTokenExpiration, tt.header) exp := parseTokenExpiration(res) if !exp.Equal(tt.want) { - t.Errorf("parseTokenExpiration returned %#v, want %#v", exp, tt.want) + t.Errorf("parseTokenExpiration of %q\nreturned %#v\n want %#v", tt.header, exp, tt.want) } } }