refactor: use http.TimeFormat as layout for http date (#57)

* refactor: use http.TimeFormat as layout for http date

* refactor: use Time.UTC instead of Time.In(time.UTC) in AppendHTTPDate
This commit is contained in:
lgbgbl 2022-06-16 16:58:08 +08:00 committed by GitHub
parent a0aa8b21ac
commit ce28dd9dd7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 55 additions and 6 deletions

View File

@ -42,12 +42,12 @@
package bytesconv
import (
"net/http"
"reflect"
"sync"
"time"
"unsafe"
"github.com/cloudwego/hertz/internal/bytestr"
"github.com/cloudwego/hertz/pkg/network"
)
@ -198,12 +198,10 @@ func AppendUint(dst []byte, n int) []byte {
return dst
}
// AppendHTTPDate appends HTTP-compliant (RFC1123) representation of date
// AppendHTTPDate appends HTTP-compliant representation of date
// to dst and returns the extended dst.
func AppendHTTPDate(dst []byte, date time.Time) []byte {
dst = date.In(time.UTC).AppendFormat(dst, time.RFC1123)
copy(dst[len(dst)-3:], bytestr.StrGMT)
return dst
return date.UTC().AppendFormat(dst, http.TimeFormat)
}
func AppendQuotedPath(dst, src []byte) []byte {

View File

@ -0,0 +1,52 @@
/*
* Copyright 2022 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package bytesconv
import (
"testing"
"time"
"github.com/cloudwego/hertz/pkg/common/test/assert"
)
func TestAppendDate(t *testing.T) {
t.Parallel()
// GMT+8
shanghaiTimeZone := time.FixedZone("Asia/Shanghai", 8*60*60)
for _, c := range []struct {
name string
date time.Time
dateStr string
}{
{
name: "UTC",
date: time.Date(2022, 6, 15, 11, 12, 13, 123, time.UTC),
dateStr: "Wed, 15 Jun 2022 11:12:13 GMT",
},
{
name: "Asia/Shanghai",
date: time.Date(2022, 6, 15, 3, 12, 45, 999, shanghaiTimeZone),
dateStr: "Tue, 14 Jun 2022 19:12:45 GMT",
},
} {
t.Run(c.name, func(t *testing.T) {
s := AppendHTTPDate(nil, c.date)
assert.DeepEqual(t, c.dateStr, string(s))
})
}
}

View File

@ -41,7 +41,6 @@ var (
StrStar = []byte("*")
StrColonSlashSlash = []byte("://")
StrColonSpace = []byte(": ")
StrGMT = []byte("GMT")
StrAt = []byte("@")
StrSD = []byte("sd")