Source file
src/net/url/url.go
Documentation: net/url
1
2
3
4
5
6 package url
7
8
9
10
11
12
13 import (
14 "bytes"
15 "errors"
16 "fmt"
17 "sort"
18 "strconv"
19 "strings"
20 )
21
22
23 type Error struct {
24 Op string
25 URL string
26 Err error
27 }
28
29 func (e *Error) Error() string { return e.Op + " " + e.URL + ": " + e.Err.Error() }
30
31 type timeout interface {
32 Timeout() bool
33 }
34
35 func (e *Error) Timeout() bool {
36 t, ok := e.Err.(timeout)
37 return ok && t.Timeout()
38 }
39
40 type temporary interface {
41 Temporary() bool
42 }
43
44 func (e *Error) Temporary() bool {
45 t, ok := e.Err.(temporary)
46 return ok && t.Temporary()
47 }
48
49 func ishex(c byte) bool {
50 switch {
51 case '0' <= c && c <= '9':
52 return true
53 case 'a' <= c && c <= 'f':
54 return true
55 case 'A' <= c && c <= 'F':
56 return true
57 }
58 return false
59 }
60
61 func unhex(c byte) byte {
62 switch {
63 case '0' <= c && c <= '9':
64 return c - '0'
65 case 'a' <= c && c <= 'f':
66 return c - 'a' + 10
67 case 'A' <= c && c <= 'F':
68 return c - 'A' + 10
69 }
70 return 0
71 }
72
73 type encoding int
74
75 const (
76 encodePath encoding = 1 + iota
77 encodePathSegment
78 encodeHost
79 encodeZone
80 encodeUserPassword
81 encodeQueryComponent
82 encodeFragment
83 )
84
85 type EscapeError string
86
87 func (e EscapeError) Error() string {
88 return "invalid URL escape " + strconv.Quote(string(e))
89 }
90
91 type InvalidHostError string
92
93 func (e InvalidHostError) Error() string {
94 return "invalid character " + strconv.Quote(string(e)) + " in host name"
95 }
96
97
98
99
100
101
102 func shouldEscape(c byte, mode encoding) bool {
103
104 if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' {
105 return false
106 }
107
108 if mode == encodeHost || mode == encodeZone {
109
110
111
112
113
114
115
116
117
118 switch c {
119 case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '[', ']', '<', '>', '"':
120 return false
121 }
122 }
123
124 switch c {
125 case '-', '_', '.', '~':
126 return false
127
128 case '$', '&', '+', ',', '/', ':', ';', '=', '?', '@':
129
130
131 switch mode {
132 case encodePath:
133
134
135
136
137 return c == '?'
138
139 case encodePathSegment:
140
141
142 return c == '/' || c == ';' || c == ',' || c == '?'
143
144 case encodeUserPassword:
145
146
147
148
149 return c == '@' || c == '/' || c == '?' || c == ':'
150
151 case encodeQueryComponent:
152
153 return true
154
155 case encodeFragment:
156
157
158 return false
159 }
160 }
161
162
163 return true
164 }
165
166
167
168
169
170
171 func QueryUnescape(s string) (string, error) {
172 return unescape(s, encodeQueryComponent)
173 }
174
175
176
177
178
179
180
181
182
183 func PathUnescape(s string) (string, error) {
184 return unescape(s, encodePathSegment)
185 }
186
187
188
189 func unescape(s string, mode encoding) (string, error) {
190
191 n := 0
192 hasPlus := false
193 for i := 0; i < len(s); {
194 switch s[i] {
195 case '%':
196 n++
197 if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) {
198 s = s[i:]
199 if len(s) > 3 {
200 s = s[:3]
201 }
202 return "", EscapeError(s)
203 }
204
205
206
207
208
209
210 if mode == encodeHost && unhex(s[i+1]) < 8 && s[i:i+3] != "%25" {
211 return "", EscapeError(s[i : i+3])
212 }
213 if mode == encodeZone {
214
215
216
217
218
219
220
221 v := unhex(s[i+1])<<4 | unhex(s[i+2])
222 if s[i:i+3] != "%25" && v != ' ' && shouldEscape(v, encodeHost) {
223 return "", EscapeError(s[i : i+3])
224 }
225 }
226 i += 3
227 case '+':
228 hasPlus = mode == encodeQueryComponent
229 i++
230 default:
231 if (mode == encodeHost || mode == encodeZone) && s[i] < 0x80 && shouldEscape(s[i], mode) {
232 return "", InvalidHostError(s[i : i+1])
233 }
234 i++
235 }
236 }
237
238 if n == 0 && !hasPlus {
239 return s, nil
240 }
241
242 t := make([]byte, len(s)-2*n)
243 j := 0
244 for i := 0; i < len(s); {
245 switch s[i] {
246 case '%':
247 t[j] = unhex(s[i+1])<<4 | unhex(s[i+2])
248 j++
249 i += 3
250 case '+':
251 if mode == encodeQueryComponent {
252 t[j] = ' '
253 } else {
254 t[j] = '+'
255 }
256 j++
257 i++
258 default:
259 t[j] = s[i]
260 j++
261 i++
262 }
263 }
264 return string(t), nil
265 }
266
267
268
269 func QueryEscape(s string) string {
270 return escape(s, encodeQueryComponent)
271 }
272
273
274
275 func PathEscape(s string) string {
276 return escape(s, encodePathSegment)
277 }
278
279 func escape(s string, mode encoding) string {
280 spaceCount, hexCount := 0, 0
281 for i := 0; i < len(s); i++ {
282 c := s[i]
283 if shouldEscape(c, mode) {
284 if c == ' ' && mode == encodeQueryComponent {
285 spaceCount++
286 } else {
287 hexCount++
288 }
289 }
290 }
291
292 if spaceCount == 0 && hexCount == 0 {
293 return s
294 }
295
296 t := make([]byte, len(s)+2*hexCount)
297 j := 0
298 for i := 0; i < len(s); i++ {
299 switch c := s[i]; {
300 case c == ' ' && mode == encodeQueryComponent:
301 t[j] = '+'
302 j++
303 case shouldEscape(c, mode):
304 t[j] = '%'
305 t[j+1] = "0123456789ABCDEF"[c>>4]
306 t[j+2] = "0123456789ABCDEF"[c&15]
307 j += 3
308 default:
309 t[j] = s[i]
310 j++
311 }
312 }
313 return string(t)
314 }
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333 type URL struct {
334 Scheme string
335 Opaque string
336 User *Userinfo
337 Host string
338 Path string
339 RawPath string
340 ForceQuery bool
341 RawQuery string
342 Fragment string
343 }
344
345
346
347 func User(username string) *Userinfo {
348 return &Userinfo{username, "", false}
349 }
350
351
352
353
354
355
356
357
358
359 func UserPassword(username, password string) *Userinfo {
360 return &Userinfo{username, password, true}
361 }
362
363
364
365
366
367 type Userinfo struct {
368 username string
369 password string
370 passwordSet bool
371 }
372
373
374 func (u *Userinfo) Username() string {
375 if u == nil {
376 return ""
377 }
378 return u.username
379 }
380
381
382 func (u *Userinfo) Password() (string, bool) {
383 if u == nil {
384 return "", false
385 }
386 return u.password, u.passwordSet
387 }
388
389
390
391 func (u *Userinfo) String() string {
392 if u == nil {
393 return ""
394 }
395 s := escape(u.username, encodeUserPassword)
396 if u.passwordSet {
397 s += ":" + escape(u.password, encodeUserPassword)
398 }
399 return s
400 }
401
402
403
404
405 func getscheme(rawurl string) (scheme, path string, err error) {
406 for i := 0; i < len(rawurl); i++ {
407 c := rawurl[i]
408 switch {
409 case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':
410
411 case '0' <= c && c <= '9' || c == '+' || c == '-' || c == '.':
412 if i == 0 {
413 return "", rawurl, nil
414 }
415 case c == ':':
416 if i == 0 {
417 return "", "", errors.New("missing protocol scheme")
418 }
419 return rawurl[:i], rawurl[i+1:], nil
420 default:
421
422
423 return "", rawurl, nil
424 }
425 }
426 return "", rawurl, nil
427 }
428
429
430
431
432 func split(s string, c string, cutc bool) (string, string) {
433 i := strings.Index(s, c)
434 if i < 0 {
435 return s, ""
436 }
437 if cutc {
438 return s[:i], s[i+len(c):]
439 }
440 return s[:i], s[i:]
441 }
442
443
444
445
446
447
448
449 func Parse(rawurl string) (*URL, error) {
450
451 u, frag := split(rawurl, "#", true)
452 url, err := parse(u, false)
453 if err != nil {
454 return nil, &Error{"parse", u, err}
455 }
456 if frag == "" {
457 return url, nil
458 }
459 if url.Fragment, err = unescape(frag, encodeFragment); err != nil {
460 return nil, &Error{"parse", rawurl, err}
461 }
462 return url, nil
463 }
464
465
466
467
468
469
470 func ParseRequestURI(rawurl string) (*URL, error) {
471 url, err := parse(rawurl, true)
472 if err != nil {
473 return nil, &Error{"parse", rawurl, err}
474 }
475 return url, nil
476 }
477
478
479
480
481
482 func parse(rawurl string, viaRequest bool) (*URL, error) {
483 var rest string
484 var err error
485
486 if rawurl == "" && viaRequest {
487 return nil, errors.New("empty url")
488 }
489 url := new(URL)
490
491 if rawurl == "*" {
492 url.Path = "*"
493 return url, nil
494 }
495
496
497
498 if url.Scheme, rest, err = getscheme(rawurl); err != nil {
499 return nil, err
500 }
501 url.Scheme = strings.ToLower(url.Scheme)
502
503 if strings.HasSuffix(rest, "?") && strings.Count(rest, "?") == 1 {
504 url.ForceQuery = true
505 rest = rest[:len(rest)-1]
506 } else {
507 rest, url.RawQuery = split(rest, "?", true)
508 }
509
510 if !strings.HasPrefix(rest, "/") {
511 if url.Scheme != "" {
512
513 url.Opaque = rest
514 return url, nil
515 }
516 if viaRequest {
517 return nil, errors.New("invalid URI for request")
518 }
519
520
521
522
523
524
525
526 colon := strings.Index(rest, ":")
527 slash := strings.Index(rest, "/")
528 if colon >= 0 && (slash < 0 || colon < slash) {
529
530 return nil, errors.New("first path segment in URL cannot contain colon")
531 }
532 }
533
534 if (url.Scheme != "" || !viaRequest && !strings.HasPrefix(rest, "///")) && strings.HasPrefix(rest, "//") {
535 var authority string
536 authority, rest = split(rest[2:], "/", false)
537 url.User, url.Host, err = parseAuthority(authority)
538 if err != nil {
539 return nil, err
540 }
541 }
542
543
544
545
546 if err := url.setPath(rest); err != nil {
547 return nil, err
548 }
549 return url, nil
550 }
551
552 func parseAuthority(authority string) (user *Userinfo, host string, err error) {
553 i := strings.LastIndex(authority, "@")
554 if i < 0 {
555 host, err = parseHost(authority)
556 } else {
557 host, err = parseHost(authority[i+1:])
558 }
559 if err != nil {
560 return nil, "", err
561 }
562 if i < 0 {
563 return nil, host, nil
564 }
565 userinfo := authority[:i]
566 if !validUserinfo(userinfo) {
567 return nil, "", errors.New("net/url: invalid userinfo")
568 }
569 if !strings.Contains(userinfo, ":") {
570 if userinfo, err = unescape(userinfo, encodeUserPassword); err != nil {
571 return nil, "", err
572 }
573 user = User(userinfo)
574 } else {
575 username, password := split(userinfo, ":", true)
576 if username, err = unescape(username, encodeUserPassword); err != nil {
577 return nil, "", err
578 }
579 if password, err = unescape(password, encodeUserPassword); err != nil {
580 return nil, "", err
581 }
582 user = UserPassword(username, password)
583 }
584 return user, host, nil
585 }
586
587
588
589 func parseHost(host string) (string, error) {
590 if strings.HasPrefix(host, "[") {
591
592
593 i := strings.LastIndex(host, "]")
594 if i < 0 {
595 return "", errors.New("missing ']' in host")
596 }
597 colonPort := host[i+1:]
598 if !validOptionalPort(colonPort) {
599 return "", fmt.Errorf("invalid port %q after host", colonPort)
600 }
601
602
603
604
605
606
607
608 zone := strings.Index(host[:i], "%25")
609 if zone >= 0 {
610 host1, err := unescape(host[:zone], encodeHost)
611 if err != nil {
612 return "", err
613 }
614 host2, err := unescape(host[zone:i], encodeZone)
615 if err != nil {
616 return "", err
617 }
618 host3, err := unescape(host[i:], encodeHost)
619 if err != nil {
620 return "", err
621 }
622 return host1 + host2 + host3, nil
623 }
624 }
625
626 var err error
627 if host, err = unescape(host, encodeHost); err != nil {
628 return "", err
629 }
630 return host, nil
631 }
632
633
634
635
636
637
638
639
640
641 func (u *URL) setPath(p string) error {
642 path, err := unescape(p, encodePath)
643 if err != nil {
644 return err
645 }
646 u.Path = path
647 if escp := escape(path, encodePath); p == escp {
648
649 u.RawPath = ""
650 } else {
651 u.RawPath = p
652 }
653 return nil
654 }
655
656
657
658
659
660
661
662
663
664
665 func (u *URL) EscapedPath() string {
666 if u.RawPath != "" && validEncodedPath(u.RawPath) {
667 p, err := unescape(u.RawPath, encodePath)
668 if err == nil && p == u.Path {
669 return u.RawPath
670 }
671 }
672 if u.Path == "*" {
673 return "*"
674 }
675 return escape(u.Path, encodePath)
676 }
677
678
679
680 func validEncodedPath(s string) bool {
681 for i := 0; i < len(s); i++ {
682
683
684
685
686
687 switch s[i] {
688 case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@':
689
690 case '[', ']':
691
692 case '%':
693
694 default:
695 if shouldEscape(s[i], encodePath) {
696 return false
697 }
698 }
699 }
700 return true
701 }
702
703
704
705 func validOptionalPort(port string) bool {
706 if port == "" {
707 return true
708 }
709 if port[0] != ':' {
710 return false
711 }
712 for _, b := range port[1:] {
713 if b < '0' || b > '9' {
714 return false
715 }
716 }
717 return true
718 }
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740 func (u *URL) String() string {
741 var buf bytes.Buffer
742 if u.Scheme != "" {
743 buf.WriteString(u.Scheme)
744 buf.WriteByte(':')
745 }
746 if u.Opaque != "" {
747 buf.WriteString(u.Opaque)
748 } else {
749 if u.Scheme != "" || u.Host != "" || u.User != nil {
750 if u.Host != "" || u.Path != "" || u.User != nil {
751 buf.WriteString("//")
752 }
753 if ui := u.User; ui != nil {
754 buf.WriteString(ui.String())
755 buf.WriteByte('@')
756 }
757 if h := u.Host; h != "" {
758 buf.WriteString(escape(h, encodeHost))
759 }
760 }
761 path := u.EscapedPath()
762 if path != "" && path[0] != '/' && u.Host != "" {
763 buf.WriteByte('/')
764 }
765 if buf.Len() == 0 {
766
767
768
769
770
771
772 if i := strings.IndexByte(path, ':'); i > -1 && strings.IndexByte(path[:i], '/') == -1 {
773 buf.WriteString("./")
774 }
775 }
776 buf.WriteString(path)
777 }
778 if u.ForceQuery || u.RawQuery != "" {
779 buf.WriteByte('?')
780 buf.WriteString(u.RawQuery)
781 }
782 if u.Fragment != "" {
783 buf.WriteByte('#')
784 buf.WriteString(escape(u.Fragment, encodeFragment))
785 }
786 return buf.String()
787 }
788
789
790
791
792
793 type Values map[string][]string
794
795
796
797
798
799 func (v Values) Get(key string) string {
800 if v == nil {
801 return ""
802 }
803 vs := v[key]
804 if len(vs) == 0 {
805 return ""
806 }
807 return vs[0]
808 }
809
810
811
812 func (v Values) Set(key, value string) {
813 v[key] = []string{value}
814 }
815
816
817
818 func (v Values) Add(key, value string) {
819 v[key] = append(v[key], value)
820 }
821
822
823 func (v Values) Del(key string) {
824 delete(v, key)
825 }
826
827
828
829
830
831
832
833
834
835
836 func ParseQuery(query string) (Values, error) {
837 m := make(Values)
838 err := parseQuery(m, query)
839 return m, err
840 }
841
842 func parseQuery(m Values, query string) (err error) {
843 for query != "" {
844 key := query
845 if i := strings.IndexAny(key, "&;"); i >= 0 {
846 key, query = key[:i], key[i+1:]
847 } else {
848 query = ""
849 }
850 if key == "" {
851 continue
852 }
853 value := ""
854 if i := strings.Index(key, "="); i >= 0 {
855 key, value = key[:i], key[i+1:]
856 }
857 key, err1 := QueryUnescape(key)
858 if err1 != nil {
859 if err == nil {
860 err = err1
861 }
862 continue
863 }
864 value, err1 = QueryUnescape(value)
865 if err1 != nil {
866 if err == nil {
867 err = err1
868 }
869 continue
870 }
871 m[key] = append(m[key], value)
872 }
873 return err
874 }
875
876
877
878 func (v Values) Encode() string {
879 if v == nil {
880 return ""
881 }
882 var buf bytes.Buffer
883 keys := make([]string, 0, len(v))
884 for k := range v {
885 keys = append(keys, k)
886 }
887 sort.Strings(keys)
888 for _, k := range keys {
889 vs := v[k]
890 prefix := QueryEscape(k) + "="
891 for _, v := range vs {
892 if buf.Len() > 0 {
893 buf.WriteByte('&')
894 }
895 buf.WriteString(prefix)
896 buf.WriteString(QueryEscape(v))
897 }
898 }
899 return buf.String()
900 }
901
902
903
904 func resolvePath(base, ref string) string {
905 var full string
906 if ref == "" {
907 full = base
908 } else if ref[0] != '/' {
909 i := strings.LastIndex(base, "/")
910 full = base[:i+1] + ref
911 } else {
912 full = ref
913 }
914 if full == "" {
915 return ""
916 }
917 var dst []string
918 src := strings.Split(full, "/")
919 for _, elem := range src {
920 switch elem {
921 case ".":
922
923 case "..":
924 if len(dst) > 0 {
925 dst = dst[:len(dst)-1]
926 }
927 default:
928 dst = append(dst, elem)
929 }
930 }
931 if last := src[len(src)-1]; last == "." || last == ".." {
932
933 dst = append(dst, "")
934 }
935 return "/" + strings.TrimPrefix(strings.Join(dst, "/"), "/")
936 }
937
938
939
940 func (u *URL) IsAbs() bool {
941 return u.Scheme != ""
942 }
943
944
945
946
947 func (u *URL) Parse(ref string) (*URL, error) {
948 refurl, err := Parse(ref)
949 if err != nil {
950 return nil, err
951 }
952 return u.ResolveReference(refurl), nil
953 }
954
955
956
957
958
959
960
961 func (u *URL) ResolveReference(ref *URL) *URL {
962 url := *ref
963 if ref.Scheme == "" {
964 url.Scheme = u.Scheme
965 }
966 if ref.Scheme != "" || ref.Host != "" || ref.User != nil {
967
968
969
970 url.setPath(resolvePath(ref.EscapedPath(), ""))
971 return &url
972 }
973 if ref.Opaque != "" {
974 url.User = nil
975 url.Host = ""
976 url.Path = ""
977 return &url
978 }
979 if ref.Path == "" && ref.RawQuery == "" {
980 url.RawQuery = u.RawQuery
981 if ref.Fragment == "" {
982 url.Fragment = u.Fragment
983 }
984 }
985
986 url.Host = u.Host
987 url.User = u.User
988 url.setPath(resolvePath(u.EscapedPath(), ref.EscapedPath()))
989 return &url
990 }
991
992
993
994
995 func (u *URL) Query() Values {
996 v, _ := ParseQuery(u.RawQuery)
997 return v
998 }
999
1000
1001
1002 func (u *URL) RequestURI() string {
1003 result := u.Opaque
1004 if result == "" {
1005 result = u.EscapedPath()
1006 if result == "" {
1007 result = "/"
1008 }
1009 } else {
1010 if strings.HasPrefix(result, "//") {
1011 result = u.Scheme + ":" + result
1012 }
1013 }
1014 if u.ForceQuery || u.RawQuery != "" {
1015 result += "?" + u.RawQuery
1016 }
1017 return result
1018 }
1019
1020
1021
1022
1023
1024
1025 func (u *URL) Hostname() string {
1026 return stripPort(u.Host)
1027 }
1028
1029
1030
1031 func (u *URL) Port() string {
1032 return portOnly(u.Host)
1033 }
1034
1035 func stripPort(hostport string) string {
1036 colon := strings.IndexByte(hostport, ':')
1037 if colon == -1 {
1038 return hostport
1039 }
1040 if i := strings.IndexByte(hostport, ']'); i != -1 {
1041 return strings.TrimPrefix(hostport[:i], "[")
1042 }
1043 return hostport[:colon]
1044 }
1045
1046 func portOnly(hostport string) string {
1047 colon := strings.IndexByte(hostport, ':')
1048 if colon == -1 {
1049 return ""
1050 }
1051 if i := strings.Index(hostport, "]:"); i != -1 {
1052 return hostport[i+len("]:"):]
1053 }
1054 if strings.Contains(hostport, "]") {
1055 return ""
1056 }
1057 return hostport[colon+len(":"):]
1058 }
1059
1060
1061
1062
1063 func (u *URL) MarshalBinary() (text []byte, err error) {
1064 return []byte(u.String()), nil
1065 }
1066
1067 func (u *URL) UnmarshalBinary(text []byte) error {
1068 u1, err := Parse(string(text))
1069 if err != nil {
1070 return err
1071 }
1072 *u = *u1
1073 return nil
1074 }
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084 func validUserinfo(s string) bool {
1085 for _, r := range s {
1086 if 'A' <= r && r <= 'Z' {
1087 continue
1088 }
1089 if 'a' <= r && r <= 'z' {
1090 continue
1091 }
1092 if '0' <= r && r <= '9' {
1093 continue
1094 }
1095 switch r {
1096 case '-', '.', '_', ':', '~', '!', '$', '&', '\'',
1097 '(', ')', '*', '+', ',', ';', '=', '%', '@':
1098 continue
1099 default:
1100 return false
1101 }
1102 }
1103 return true
1104 }
1105
View as plain text