-
Notifications
You must be signed in to change notification settings - Fork 558
/
Copy pathheader.go
1592 lines (1383 loc) · 43.4 KB
/
header.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.
*
* The MIT License (MIT)
*
* Copyright (c) 2015-present Aliaksandr Valialkin, VertaMedia, Kirill Danshin, Erik Dubbelboer, FastHTTP Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file may have been modified by CloudWeGo authors. All CloudWeGo
* Modifications are Copyright 2022 CloudWeGo Authors.
*/
package protocol
import (
"bytes"
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/cloudwego/hertz/internal/bytesconv"
"github.com/cloudwego/hertz/internal/bytestr"
"github.com/cloudwego/hertz/internal/nocopy"
errs "github.com/cloudwego/hertz/pkg/common/errors"
"github.com/cloudwego/hertz/pkg/common/hlog"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/protocol/consts"
)
var (
ServerDate atomic.Value
ServerDateOnce sync.Once // serverDateOnce.Do(updateServerDate)
)
type RequestHeader struct {
noCopy nocopy.NoCopy //lint:ignore U1000 until noCopy is used
disableNormalizing bool
noHTTP11 bool
protocol string
connectionClose bool
noDefaultContentType bool
// These two fields have been moved close to other bool fields
// for reducing RequestHeader object size.
cookiesCollected bool
contentLength int
contentLengthBytes []byte
method []byte
requestURI []byte
host []byte
contentType []byte
userAgent []byte
h []argsKV
bufKV argsKV
cookies []argsKV
// stores an immutable copy of headers as they were received from the
// wire.
rawHeaders []byte
}
func (h *RequestHeader) SetRawHeaders(r []byte) {
h.rawHeaders = r
}
// ResponseHeader represents HTTP response header.
//
// It is forbidden copying ResponseHeader instances.
// Create new instances instead and use CopyTo.
//
// ResponseHeader instance MUST NOT be used from concurrently running
// goroutines.
type ResponseHeader struct {
noCopy nocopy.NoCopy //lint:ignore U1000 until noCopy is used
disableNormalizing bool
noHTTP11 bool
connectionClose bool
noDefaultContentType bool
noDefaultDate bool
statusCode int
contentLength int
contentLengthBytes []byte
contentType []byte
server []byte
h []argsKV
bufKV argsKV
cookies []argsKV
headerLength int
}
// SetHeaderLength sets the size of header for tracer.
func (h *ResponseHeader) SetHeaderLength(length int) {
h.headerLength = length
}
// GetHeaderLength gets the size of header for tracer.
func (h *ResponseHeader) GetHeaderLength() int {
return h.headerLength
}
// SetContentRange sets 'Content-Range: bytes startPos-endPos/contentLength'
// header.
func (h *ResponseHeader) SetContentRange(startPos, endPos, contentLength int) {
b := h.bufKV.value[:0]
b = append(b, bytestr.StrBytes...)
b = append(b, ' ')
b = bytesconv.AppendUint(b, startPos)
b = append(b, '-')
b = bytesconv.AppendUint(b, endPos)
b = append(b, '/')
b = bytesconv.AppendUint(b, contentLength)
h.bufKV.value = b
h.SetCanonical(bytestr.StrContentRange, h.bufKV.value)
}
func (h *ResponseHeader) NoDefaultContentType() bool {
return h.noDefaultContentType
}
// SetConnectionClose sets 'Connection: close' header.
func (h *ResponseHeader) SetConnectionClose(close bool) {
h.connectionClose = close
}
func (h *ResponseHeader) PeekArgBytes(key []byte) []byte {
return peekArgBytes(h.h, key)
}
func (h *ResponseHeader) SetNoHTTP11(b bool) {
h.noHTTP11 = b
}
// Cookie fills cookie for the given cookie.Key.
//
// Returns false if cookie with the given cookie.Key is missing.
func (h *ResponseHeader) Cookie(cookie *Cookie) bool {
v := peekArgBytes(h.cookies, cookie.Key())
if v == nil {
return false
}
cookie.ParseBytes(v) //nolint:errcheck
return true
}
// FullCookie returns complete cookie bytes
func (h *ResponseHeader) FullCookie() []byte {
return h.Peek(consts.HeaderSetCookie)
}
// IsHTTP11 returns true if the response is HTTP/1.1.
func (h *ResponseHeader) IsHTTP11() bool {
return !h.noHTTP11
}
// SetContentType sets Content-Type header value.
func (h *ResponseHeader) SetContentType(contentType string) {
h.contentType = append(h.contentType[:0], contentType...)
}
func (h *ResponseHeader) GetHeaders() []argsKV {
return h.h
}
// Reset clears response header.
func (h *ResponseHeader) Reset() {
h.disableNormalizing = false
h.noDefaultContentType = false
h.noDefaultDate = false
h.ResetSkipNormalize()
}
// CopyTo copies all the headers to dst.
func (h *ResponseHeader) CopyTo(dst *ResponseHeader) {
dst.Reset()
dst.disableNormalizing = h.disableNormalizing
dst.noHTTP11 = h.noHTTP11
dst.connectionClose = h.connectionClose
dst.noDefaultContentType = h.noDefaultContentType
dst.noDefaultDate = h.noDefaultDate
dst.statusCode = h.statusCode
dst.contentLength = h.contentLength
dst.contentLengthBytes = append(dst.contentLengthBytes[:0], h.contentLengthBytes...)
dst.contentType = append(dst.contentType[:0], h.contentType...)
dst.server = append(dst.server[:0], h.server...)
dst.h = copyArgs(dst.h, h.h)
dst.cookies = copyArgs(dst.cookies, h.cookies)
}
//
// Multiple headers with the same key may be added with this function.
// Use Set for setting a single header for the given key.
//
// the Content-Type, Content-Length, Connection, Cookie,
// Transfer-Encoding, Host and User-Agent headers can only be set once
// and will overwrite the previous value.
func (h *RequestHeader) Add(key, value string) {
if h.setSpecialHeader(bytesconv.S2b(key), bytesconv.S2b(value)) {
return
}
k := getHeaderKeyBytes(&h.bufKV, key, h.disableNormalizing)
h.h = appendArg(h.h, bytesconv.B2s(k), value, ArgsHasValue)
}
// VisitAll calls f for each header.
//
// f must not retain references to key and/or value after returning.
// Copy key and/or value contents before returning if you need retaining them.
func (h *ResponseHeader) VisitAll(f func(key, value []byte)) {
if len(h.contentLengthBytes) > 0 {
f(bytestr.StrContentLength, h.contentLengthBytes)
}
contentType := h.ContentType()
if len(contentType) > 0 {
f(bytestr.StrContentType, contentType)
}
server := h.Server()
if len(server) > 0 {
f(bytestr.StrServer, server)
}
if len(h.cookies) > 0 {
visitArgs(h.cookies, func(k, v []byte) {
f(bytestr.StrSetCookie, v)
})
}
visitArgs(h.h, f)
if h.ConnectionClose() {
f(bytestr.StrConnection, bytestr.StrClose)
}
}
// IsHTTP11 returns true if the request is HTTP/1.1.
func (h *RequestHeader) IsHTTP11() bool {
return !h.noHTTP11
}
func (h *RequestHeader) SetProtocol(p string) {
h.protocol = p
}
func (h *RequestHeader) GetProtocol() string {
return h.protocol
}
func (h *RequestHeader) SetNoHTTP11(b bool) {
h.noHTTP11 = b
}
func (h *RequestHeader) InitBufValue(size int) {
if size > cap(h.bufKV.value) {
h.bufKV.value = make([]byte, 0, size)
}
}
func (h *RequestHeader) GetBufValue() []byte {
return h.bufKV.value
}
// HasAcceptEncodingBytes returns true if the header contains
// the given Accept-Encoding value.
func (h *RequestHeader) HasAcceptEncodingBytes(acceptEncoding []byte) bool {
ae := h.peek(bytestr.StrAcceptEncoding)
n := bytes.Index(ae, acceptEncoding)
if n < 0 {
return false
}
b := ae[n+len(acceptEncoding):]
if len(b) > 0 && b[0] != ',' {
return false
}
if n == 0 {
return true
}
return ae[n-1] == ' '
}
func (h *RequestHeader) PeekIfModifiedSinceBytes() []byte {
return h.peek(bytestr.StrIfModifiedSince)
}
// RequestURI returns RequestURI from the first HTTP request line.
func (h *RequestHeader) RequestURI() []byte {
requestURI := h.requestURI
if len(requestURI) == 0 {
requestURI = bytestr.StrSlash
}
return requestURI
}
func (h *RequestHeader) PeekArgBytes(key []byte) []byte {
return peekArgBytes(h.h, key)
}
// RawHeaders returns raw header key/value bytes.
//
// Depending on server configuration, header keys may be normalized to
// capital-case in place.
//
// This copy is set aside during parsing, so empty slice is returned for all
// cases where parsing did not happen. Similarly, request line is not stored
// during parsing and can not be returned.
//
// The slice is not safe to use after the handler returns.
func (h *RequestHeader) RawHeaders() []byte {
return h.rawHeaders
}
// AppendBytes appends request header representation to dst and returns
// the extended dst.
func (h *RequestHeader) AppendBytes(dst []byte) []byte {
dst = append(dst, h.Method()...)
dst = append(dst, ' ')
dst = append(dst, h.RequestURI()...)
dst = append(dst, ' ')
dst = append(dst, bytestr.StrHTTP11...)
dst = append(dst, bytestr.StrCRLF...)
userAgent := h.UserAgent()
if len(userAgent) > 0 {
dst = appendHeaderLine(dst, bytestr.StrUserAgent, userAgent)
}
host := h.Host()
if len(host) > 0 {
dst = appendHeaderLine(dst, bytestr.StrHost, host)
}
contentType := h.ContentType()
if len(contentType) == 0 && !h.IgnoreBody() && !h.noDefaultContentType {
contentType = bytestr.StrPostArgsContentType
}
if len(contentType) > 0 {
dst = appendHeaderLine(dst, bytestr.StrContentType, contentType)
}
if len(h.contentLengthBytes) > 0 {
dst = appendHeaderLine(dst, bytestr.StrContentLength, h.contentLengthBytes)
}
for i, n := 0, len(h.h); i < n; i++ {
kv := &h.h[i]
dst = appendHeaderLine(dst, kv.key, kv.value)
}
// there is no need in h.collectCookies() here, since if cookies aren't collected yet,
// they all are located in h.h.
n := len(h.cookies)
if n > 0 {
dst = append(dst, bytestr.StrCookie...)
dst = append(dst, bytestr.StrColonSpace...)
dst = appendRequestCookieBytes(dst, h.cookies)
dst = append(dst, bytestr.StrCRLF...)
}
if h.ConnectionClose() {
dst = appendHeaderLine(dst, bytestr.StrConnection, bytestr.StrClose)
}
return append(dst, bytestr.StrCRLF...)
}
// Header returns request header representation.
//
// The returned representation is valid until the next call to RequestHeader methods.
func (h *RequestHeader) Header() []byte {
h.bufKV.value = h.AppendBytes(h.bufKV.value[:0])
return h.bufKV.value
}
// IsPut returns true if request method is PUT.
func (h *RequestHeader) IsPut() bool {
return bytes.Equal(h.Method(), bytestr.StrPut)
}
// IsHead returns true if request method is HEAD.
func (h *RequestHeader) IsHead() bool {
return bytes.Equal(h.Method(), bytestr.StrHead)
}
// IsPost returns true if request method is POST.
func (h *RequestHeader) IsPost() bool {
return bytes.Equal(h.Method(), bytestr.StrPost)
}
// IsDelete returns true if request method is DELETE.
func (h *RequestHeader) IsDelete() bool {
return bytes.Equal(h.Method(), bytestr.StrDelete)
}
// IsConnect returns true if request method is CONNECT.
func (h *RequestHeader) IsConnect() bool {
return bytes.Equal(h.Method(), bytestr.StrConnect)
}
func (h *RequestHeader) IgnoreBody() bool {
return h.IsGet() || h.IsHead()
}
// ContentLength returns Content-Length header value.
//
// It may be negative:
// -1 means Transfer-Encoding: chunked.
func (h *RequestHeader) ContentLength() int {
return h.contentLength
}
// SetHost sets Host header value.
func (h *RequestHeader) SetHost(host string) {
h.host = append(h.host[:0], host...)
}
// SetStatusCode sets response status code.
func (h *ResponseHeader) SetStatusCode(statusCode int) {
checkWriteHeaderCode(statusCode)
h.statusCode = statusCode
}
func checkWriteHeaderCode(code int) {
// For now, we only emit a warning for bad codes.
// In the future we might block things over 599 or under 100
if code < 100 || code > 599 {
hlog.SystemLogger().Warnf("Invalid StatusCode code %v, status code should not be under 100 or over 599.\n"+
"For more info: https://www.rfc-editor.org/rfc/rfc9110.html#name-status-codes", code)
}
}
func (h *ResponseHeader) ResetSkipNormalize() {
h.noHTTP11 = false
h.connectionClose = false
h.statusCode = 0
h.contentLength = 0
h.contentLengthBytes = h.contentLengthBytes[:0]
h.contentType = h.contentType[:0]
h.server = h.server[:0]
h.h = h.h[:0]
h.cookies = h.cookies[:0]
}
// ContentLength returns Content-Length header value.
//
// It may be negative:
// -1 means Transfer-Encoding: chunked.
// -2 means Transfer-Encoding: identity.
func (h *ResponseHeader) ContentLength() int {
return h.contentLength
}
// Set sets the given 'key: value' header.
//
// Use Add for setting multiple header values under the same key.
func (h *ResponseHeader) Set(key, value string) {
initHeaderKV(&h.bufKV, key, value, h.disableNormalizing)
h.SetCanonical(h.bufKV.key, h.bufKV.value)
}
// Add adds the given 'key: value' header.
//
// Multiple headers with the same key may be added with this function.
// Use Set for setting a single header for the given key.
//
// the Content-Type, Content-Length, Connection, Server, Set-Cookie,
// Transfer-Encoding and Date headers can only be set once and will
// overwrite the previous value.
func (h *ResponseHeader) Add(key, value string) {
if h.setSpecialHeader(bytesconv.S2b(key), bytesconv.S2b(value)) {
return
}
k := getHeaderKeyBytes(&h.bufKV, key, h.disableNormalizing)
h.h = appendArg(h.h, bytesconv.B2s(k), value, ArgsHasValue)
}
// SetContentLength sets Content-Length header value.
//
// Content-Length may be negative:
// -1 means Transfer-Encoding: chunked.
// -2 means Transfer-Encoding: identity.
func (h *ResponseHeader) SetContentLength(contentLength int) {
if h.MustSkipContentLength() {
return
}
h.contentLength = contentLength
if contentLength >= 0 {
h.contentLengthBytes = bytesconv.AppendUint(h.contentLengthBytes[:0], contentLength)
h.h = delAllArgsBytes(h.h, bytestr.StrTransferEncoding)
} else {
h.contentLengthBytes = h.contentLengthBytes[:0]
value := bytestr.StrChunked
if contentLength == -2 {
h.SetConnectionClose(true)
value = bytestr.StrIdentity
}
h.h = setArgBytes(h.h, bytestr.StrTransferEncoding, value, ArgsHasValue)
}
}
func (h *ResponseHeader) ContentLengthBytes() []byte {
return h.contentLengthBytes
}
func (h *ResponseHeader) InitContentLengthWithValue(contentLength int) {
h.contentLength = contentLength
}
// VisitAllCookie calls f for each response cookie.
//
// Cookie name is passed in key and the whole Set-Cookie header value
// is passed in value on each f invocation. Value may be parsed
// with Cookie.ParseBytes().
//
// f must not retain references to key and/or value after returning.
func (h *ResponseHeader) VisitAllCookie(f func(key, value []byte)) {
visitArgs(h.cookies, f)
}
// DelAllCookies removes all the cookies from response headers.
func (h *ResponseHeader) DelAllCookies() {
h.cookies = h.cookies[:0]
}
// DelCookie removes cookie under the given key from response header.
//
// Note that DelCookie doesn't remove the cookie from the client.
// Use DelClientCookie instead.
func (h *ResponseHeader) DelCookie(key string) {
h.cookies = delAllArgs(h.cookies, key)
}
// DelCookieBytes removes cookie under the given key from response header.
//
// Note that DelCookieBytes doesn't remove the cookie from the client.
// Use DelClientCookieBytes instead.
func (h *ResponseHeader) DelCookieBytes(key []byte) {
h.DelCookie(bytesconv.B2s(key))
}
// DelBytes deletes header with the given key.
func (h *ResponseHeader) DelBytes(key []byte) {
h.bufKV.key = append(h.bufKV.key[:0], key...)
utils.NormalizeHeaderKey(h.bufKV.key, h.disableNormalizing)
h.del(h.bufKV.key)
}
// Header returns response header representation.
//
// The returned value is valid until the next call to ResponseHeader methods.
func (h *ResponseHeader) Header() []byte {
h.bufKV.value = h.AppendBytes(h.bufKV.value[:0])
return h.bufKV.value
}
func (h *ResponseHeader) PeekLocation() []byte {
return h.peek(bytestr.StrLocation)
}
// DelClientCookie instructs the client to remove the given cookie.
// This doesn't work for a cookie with specific domain or path,
// you should delete it manually like:
//
// c := AcquireCookie()
// c.SetKey(key)
// c.SetDomain("example.com")
// c.SetPath("/path")
// c.SetExpire(CookieExpireDelete)
// h.SetCookie(c)
// ReleaseCookie(c)
//
// Use DelCookie if you want just removing the cookie from response header.
func (h *ResponseHeader) DelClientCookie(key string) {
h.DelCookie(key)
c := AcquireCookie()
c.SetKey(key)
c.SetExpire(CookieExpireDelete)
h.SetCookie(c)
ReleaseCookie(c)
}
// DelClientCookieBytes instructs the client to remove the given cookie.
// This doesn't work for a cookie with specific domain or path,
// you should delete it manually like:
//
// c := AcquireCookie()
// c.SetKey(key)
// c.SetDomain("example.com")
// c.SetPath("/path")
// c.SetExpire(CookieExpireDelete)
// h.SetCookie(c)
// ReleaseCookie(c)
//
// Use DelCookieBytes if you want just removing the cookie from response header.
func (h *ResponseHeader) DelClientCookieBytes(key []byte) {
h.DelClientCookie(bytesconv.B2s(key))
}
// Peek returns header value for the given key.
//
// Returned value is valid until the next call to ResponseHeader.
// Do not store references to returned value. Make copies instead.
func (h *ResponseHeader) Peek(key string) []byte {
k := getHeaderKeyBytes(&h.bufKV, key, h.disableNormalizing)
return h.peek(k)
}
func (h *ResponseHeader) IsDisableNormalizing() bool {
return h.disableNormalizing
}
func (h *ResponseHeader) ParseSetCookie(value []byte) {
var kv *argsKV
h.cookies, kv = allocArg(h.cookies)
kv.key = getCookieKey(kv.key, value)
kv.value = append(kv.value[:0], value...)
}
func (h *ResponseHeader) peek(key []byte) []byte {
switch string(key) {
case consts.HeaderContentType:
return h.ContentType()
case consts.HeaderServer:
return h.Server()
case consts.HeaderConnection:
if h.ConnectionClose() {
return bytestr.StrClose
}
return peekArgBytes(h.h, key)
case consts.HeaderContentLength:
return h.contentLengthBytes
case consts.HeaderSetCookie:
return appendResponseCookieBytes(nil, h.cookies)
default:
return peekArgBytes(h.h, key)
}
}
// SetContentTypeBytes sets Content-Type header value.
func (h *ResponseHeader) SetContentTypeBytes(contentType []byte) {
h.contentType = append(h.contentType[:0], contentType...)
}
func (h *ResponseHeader) SetContentLengthBytes(contentLength []byte) {
h.contentLengthBytes = append(h.contentLengthBytes[:0], contentLength...)
}
// SetCanonical sets the given 'key: value' header assuming that
// key is in canonical form.
func (h *ResponseHeader) SetCanonical(key, value []byte) {
if h.setSpecialHeader(key, value) {
return
}
h.h = setArgBytes(h.h, key, value, ArgsHasValue)
}
// ResetConnectionClose clears 'Connection: close' header if it exists.
func (h *ResponseHeader) ResetConnectionClose() {
if h.connectionClose {
h.connectionClose = false
h.h = delAllArgsBytes(h.h, bytestr.StrConnection)
}
}
// Server returns Server header value.
func (h *ResponseHeader) Server() []byte {
return h.server
}
func (h *ResponseHeader) AddArgBytes(key, value []byte, noValue bool) {
h.h = appendArgBytes(h.h, key, value, noValue)
}
func (h *ResponseHeader) SetArgBytes(key, value []byte, noValue bool) {
h.h = setArgBytes(h.h, key, value, noValue)
}
// AppendBytes appends response header representation to dst and returns
// the extended dst.
func (h *ResponseHeader) AppendBytes(dst []byte) []byte {
statusCode := h.StatusCode()
if statusCode < 0 {
statusCode = consts.StatusOK
}
dst = append(dst, consts.StatusLine(statusCode)...)
server := h.Server()
if len(server) != 0 {
dst = appendHeaderLine(dst, bytestr.StrServer, server)
}
if !h.noDefaultDate {
ServerDateOnce.Do(UpdateServerDate)
dst = appendHeaderLine(dst, bytestr.StrDate, ServerDate.Load().([]byte))
}
// Append Content-Type only for non-zero responses
// or if it is explicitly set.
if h.ContentLength() != 0 || len(h.contentType) > 0 {
contentType := h.ContentType()
if len(contentType) > 0 {
dst = appendHeaderLine(dst, bytestr.StrContentType, contentType)
}
}
if len(h.contentLengthBytes) > 0 {
dst = appendHeaderLine(dst, bytestr.StrContentLength, h.contentLengthBytes)
}
for i, n := 0, len(h.h); i < n; i++ {
kv := &h.h[i]
if h.noDefaultDate || !bytes.Equal(kv.key, bytestr.StrDate) {
dst = appendHeaderLine(dst, kv.key, kv.value)
}
}
n := len(h.cookies)
if n > 0 {
for i := 0; i < n; i++ {
kv := &h.cookies[i]
dst = appendHeaderLine(dst, bytestr.StrSetCookie, kv.value)
}
}
if h.ConnectionClose() {
dst = appendHeaderLine(dst, bytestr.StrConnection, bytestr.StrClose)
}
return append(dst, bytestr.StrCRLF...)
}
// ConnectionClose returns true if 'Connection: close' header is set.
func (h *ResponseHeader) ConnectionClose() bool {
return h.connectionClose
}
func (h *ResponseHeader) GetCookies() []argsKV {
return h.cookies
}
// ContentType returns Content-Type header value.
func (h *ResponseHeader) ContentType() []byte {
contentType := h.contentType
if !h.noDefaultContentType && len(h.contentType) == 0 {
contentType = bytestr.DefaultContentType
}
return contentType
}
// SetNoDefaultContentType set noDefaultContentType value of ResponseHeader.
func (h *ResponseHeader) SetNoDefaultContentType(b bool) {
h.noDefaultContentType = b
}
// SetServerBytes sets Server header value.
func (h *ResponseHeader) SetServerBytes(server []byte) {
h.server = append(h.server[:0], server...)
}
func (h *ResponseHeader) MustSkipContentLength() bool {
// From http/1.1 specs:
// All 1xx (informational), 204 (no content), and 304 (not modified) responses MUST NOT include a message-body
statusCode := h.StatusCode()
// Fast path.
if statusCode < 100 || statusCode == consts.StatusOK {
return false
}
// Slow path.
return statusCode == consts.StatusNotModified || statusCode == consts.StatusNoContent || statusCode < 200
}
// StatusCode returns response status code.
func (h *ResponseHeader) StatusCode() int {
if h.statusCode == 0 {
return consts.StatusOK
}
return h.statusCode
}
// Del deletes header with the given key.
func (h *ResponseHeader) Del(key string) {
k := getHeaderKeyBytes(&h.bufKV, key, h.disableNormalizing)
h.del(k)
}
func (h *ResponseHeader) del(key []byte) {
switch string(key) {
case consts.HeaderContentType:
h.contentType = h.contentType[:0]
case consts.HeaderServer:
h.server = h.server[:0]
case consts.HeaderSetCookie:
h.cookies = h.cookies[:0]
case consts.HeaderContentLength:
h.contentLength = 0
h.contentLengthBytes = h.contentLengthBytes[:0]
case consts.HeaderConnection:
h.connectionClose = false
}
h.h = delAllArgsBytes(h.h, key)
}
// SetBytesV sets the given 'key: value' header.
//
// Use AddBytesV for setting multiple header values under the same key.
func (h *ResponseHeader) SetBytesV(key string, value []byte) {
k := getHeaderKeyBytes(&h.bufKV, key, h.disableNormalizing)
h.SetCanonical(k, value)
}
// Len returns the number of headers set,
// i.e. the number of times f is called in VisitAll.
func (h *ResponseHeader) Len() int {
n := 0
h.VisitAll(func(k, v []byte) { n++ })
return n
}
// Len returns the number of headers set,
// i.e. the number of times f is called in VisitAll.
func (h *RequestHeader) Len() int {
n := 0
h.VisitAll(func(k, v []byte) { n++ })
return n
}
// Reset clears request header.
func (h *RequestHeader) Reset() {
h.disableNormalizing = false
h.ResetSkipNormalize()
}
// SetByteRange sets 'Range: bytes=startPos-endPos' header.
//
// * If startPos is negative, then 'bytes=-startPos' value is set.
// * If endPos is negative, then 'bytes=startPos-' value is set.
func (h *RequestHeader) SetByteRange(startPos, endPos int) {
b := h.bufKV.value[:0]
b = append(b, bytestr.StrBytes...)
b = append(b, '=')
if startPos >= 0 {
b = bytesconv.AppendUint(b, startPos)
} else {
endPos = -startPos
}
b = append(b, '-')
if endPos >= 0 {
b = bytesconv.AppendUint(b, endPos)
}
h.bufKV.value = b
h.SetCanonical(bytestr.StrRange, h.bufKV.value)
}
// DelBytes deletes header with the given key.
func (h *RequestHeader) DelBytes(key []byte) {
h.bufKV.key = append(h.bufKV.key[:0], key...)
utils.NormalizeHeaderKey(h.bufKV.key, h.disableNormalizing)
h.del(h.bufKV.key)
}
func (h *RequestHeader) SetArgBytes(key, value []byte, noValue bool) {
h.h = setArgBytes(h.h, key, value, noValue)
}
func (h *RequestHeader) del(key []byte) {
switch string(key) {
case consts.HeaderHost:
h.host = h.host[:0]
case consts.HeaderContentType:
h.contentType = h.contentType[:0]
case consts.HeaderUserAgent:
h.userAgent = h.userAgent[:0]
case consts.HeaderCookie:
h.cookies = h.cookies[:0]
case consts.HeaderContentLength:
h.contentLength = 0
h.contentLengthBytes = h.contentLengthBytes[:0]
case consts.HeaderConnection:
h.connectionClose = false
}
h.h = delAllArgsBytes(h.h, key)
}
// CopyTo copies all the headers to dst.
func (h *RequestHeader) CopyTo(dst *RequestHeader) {
dst.Reset()
dst.disableNormalizing = h.disableNormalizing
dst.noHTTP11 = h.noHTTP11
dst.connectionClose = h.connectionClose
dst.noDefaultContentType = h.noDefaultContentType
dst.contentLength = h.contentLength
dst.contentLengthBytes = append(dst.contentLengthBytes[:0], h.contentLengthBytes...)
dst.method = append(dst.method[:0], h.method...)
dst.requestURI = append(dst.requestURI[:0], h.requestURI...)
dst.host = append(dst.host[:0], h.host...)
dst.contentType = append(dst.contentType[:0], h.contentType...)
dst.userAgent = append(dst.userAgent[:0], h.userAgent...)
dst.h = copyArgs(dst.h, h.h)
dst.cookies = copyArgs(dst.cookies, h.cookies)
dst.cookiesCollected = h.cookiesCollected
dst.rawHeaders = append(dst.rawHeaders[:0], h.rawHeaders...)
}
// Peek returns header value for the given key.
//
// Returned value is valid until the next call to RequestHeader.
// Do not store references to returned value. Make copies instead.
func (h *RequestHeader) Peek(key string) []byte {
k := getHeaderKeyBytes(&h.bufKV, key, h.disableNormalizing)
return h.peek(k)
}
// SetMultipartFormBoundary sets the following Content-Type:
// 'multipart/form-data; boundary=...'
// where ... is substituted by the given boundary.
func (h *RequestHeader) SetMultipartFormBoundary(boundary string) {
b := h.bufKV.value[:0]
b = append(b, bytestr.StrMultipartFormData...)
b = append(b, ';', ' ')
b = append(b, bytestr.StrBoundary...)
b = append(b, '=')
b = append(b, boundary...)
h.bufKV.value = b
h.SetContentTypeBytes(h.bufKV.value)
}
func (h *RequestHeader) ContentLengthBytes() []byte {
return h.contentLengthBytes
}
func (h *RequestHeader) SetContentLengthBytes(contentLength []byte) {
h.contentLengthBytes = append(h.contentLengthBytes[:0], contentLength...)
}
// SetContentTypeBytes sets Content-Type header value.
func (h *RequestHeader) SetContentTypeBytes(contentType []byte) {
h.contentType = append(h.contentType[:0], contentType...)
}
// ContentType returns Content-Type header value.
func (h *RequestHeader) ContentType() []byte {
return h.contentType
}
// SetNoDefaultContentType controls the default Content-Type header behaviour.
//
// When set to false, the Content-Type header is sent with a default value if no Content-Type value is specified.
// When set to true, no Content-Type header is sent if no Content-Type value is specified.
func (h *RequestHeader) SetNoDefaultContentType(b bool) {
h.noDefaultContentType = b