File: url.go

package info (click to toggle)
golang-github-anacrolix-missinggo 2.1.0-7
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 872 kB
  • sloc: makefile: 4
file content (64 lines) | stat: -rw-r--r-- 1,866 bytes parent folder | download | duplicates (2)
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
package httptoo

import (
	"net/http"
	"net/url"
)

// Deep copies a URL. I could call it DeepCopyURL, but what else would you be
// copying when you have a *url.URL? Of note is that the Userinfo is deep
// copied. The returned URL shares no references with the original.
func CopyURL(u *url.URL) (ret *url.URL) {
	ret = new(url.URL)
	*ret = *u
	if u.User != nil {
		ret.User = new(url.Userinfo)
		*ret.User = *u.User
	}
	return
}

// Reconstructs the URL that would have produced the given Request.
// Request.URLs are not fully populated in http.Server handlers.
func RequestedURL(r *http.Request) (ret *url.URL) {
	ret = CopyURL(r.URL)
	ret.Host = r.Host
	ret.Scheme = OriginatingProtocol(r)
	return
}

// The official URL struct parameters, for tracking changes and reference
// here.
//
// 	Scheme     string
// 	Opaque     string    // encoded opaque data
// 	User       *Userinfo // username and password information
// 	Host       string    // host or host:port
// 	Path       string
// 	RawPath    string // encoded path hint (Go 1.5 and later only; see EscapedPath method)
// 	ForceQuery bool   // append a query ('?') even if RawQuery is empty
// 	RawQuery   string // encoded query values, without '?'
// 	Fragment   string // fragment for references, without '#'

// Return the first URL extended with elements of the second, in the manner
// that occurs throughout my projects. Noteworthy difference from
// url.URL.ResolveReference is that if the reference has a scheme, the base is
// not completely ignored.
func AppendURL(u, v *url.URL) *url.URL {
	u = CopyURL(u)
	clobberString(&u.Scheme, v.Scheme)
	clobberString(&u.Host, v.Host)
	u.Path += v.Path
	q := u.Query()
	for k, v := range v.Query() {
		q[k] = append(q[k], v...)
	}
	u.RawQuery = q.Encode()
	return u
}

func clobberString(s *string, value string) {
	if value != "" {
		*s = value
	}
}