File: url.go

package info (click to toggle)
incus 6.0.4-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 23,864 kB
  • sloc: sh: 16,015; ansic: 3,121; python: 456; makefile: 321; ruby: 51; sql: 50; lisp: 6
file content (82 lines) | stat: -rw-r--r-- 1,981 bytes parent folder | download | duplicates (3)
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
package api

import (
	"net/url"
	"strings"
)

// URL represents an endpoint for the REST API.
type URL struct {
	url.URL
}

// NewURL creates a new URL.
func NewURL() *URL {
	return &URL{}
}

// Scheme sets the scheme of the URL.
func (u *URL) Scheme(scheme string) *URL {
	u.URL.Scheme = scheme

	return u
}

// Host sets the host of the URL.
func (u *URL) Host(host string) *URL {
	u.URL.Host = host

	return u
}

// Path sets the path of the URL from one or more path parts.
// It appends each of the pathParts (escaped using url.PathEscape) prefixed with "/" to the URL path.
func (u *URL) Path(pathParts ...string) *URL {
	var path, rawPath strings.Builder

	for _, pathPart := range pathParts {
		// Generate unencoded path.
		path.WriteString("/") // Build an absolute URL.
		path.WriteString(pathPart)

		// Generate encoded path hint (this will be used by u.URL.EncodedPath() to decide its methodology).
		rawPath.WriteString("/") // Build an absolute URL.
		rawPath.WriteString(url.PathEscape(pathPart))
	}

	u.URL.Path = path.String()
	u.URL.RawPath = rawPath.String()

	return u
}

// Project sets the "project" query parameter in the URL if the projectName is not empty or "default".
func (u *URL) Project(projectName string) *URL {
	if projectName != "default" && projectName != "" {
		queryArgs := u.Query()
		queryArgs.Add("project", projectName)
		u.RawQuery = queryArgs.Encode()
	}

	return u
}

// Target sets the "target" query parameter in the URL if the clusterMemberName is not empty or "default".
func (u *URL) Target(clusterMemberName string) *URL {
	if clusterMemberName != "" && clusterMemberName != "none" {
		queryArgs := u.Query()
		queryArgs.Add("target", clusterMemberName)
		u.RawQuery = queryArgs.Encode()
	}

	return u
}

// WithQuery adds a given query parameter with its value to the URL.
func (u *URL) WithQuery(key string, value string) *URL {
	queryArgs := u.Query()
	queryArgs.Add(key, value)
	u.RawQuery = queryArgs.Encode()

	return u
}