File: urlpart.go

package info (click to toggle)
golang-github-nicholas-fedor-shoutrrr 0.8.18-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 4,328 kB
  • sloc: sh: 61; makefile: 5
file content (84 lines) | stat: -rw-r--r-- 1,805 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//go:generate stringer -type=URLPart -trimprefix URL

package format

import (
	"log"
	"strconv"
	"strings"
)

// URLPart is an indicator as to what part of an URL a field is serialized to.
type URLPart int

// Suffix returns the separator between the URLPart and its subsequent part.
func (u URLPart) Suffix() rune {
	switch u {
	case URLQuery:
		return '/'
	case URLUser:
		return ':'
	case URLPassword:
		return '@'
	case URLHost:
		return ':'
	case URLPort:
		return '/'
	case URLPath:
		return '/'
	default:
		return '/'
	}
}

// indicator as to what part of an URL a field is serialized to.
const (
	URLQuery URLPart = iota
	URLUser
	URLPassword
	URLHost
	URLPort
	URLPath // Base path; additional paths are URLPath + N
)

// ParseURLPart returns the URLPart that matches the supplied string.
func ParseURLPart(inputString string) URLPart {
	lowerString := strings.ToLower(inputString)
	switch lowerString {
	case "user":
		return URLUser
	case "pass", "password":
		return URLPassword
	case "host":
		return URLHost
	case "port":
		return URLPort
	case "path", "path1":
		return URLPath
	case "query", "":
		return URLQuery
	}

	// Handle dynamic path segments (e.g., "path2", "path3", etc.).
	if strings.HasPrefix(lowerString, "path") && len(lowerString) > 4 {
		if num, err := strconv.Atoi(lowerString[4:]); err == nil && num >= 2 {
			return URLPath + URLPart(num-1) // Offset from URLPath; "path2" -> URLPath+1
		}
	}

	log.Printf("invalid URLPart: %s, defaulting to URLQuery", lowerString)

	return URLQuery
}

// ParseURLParts returns the URLParts that matches the supplied string.
func ParseURLParts(s string) []URLPart {
	rawParts := strings.Split(s, ",")
	urlParts := make([]URLPart, len(rawParts))

	for i, raw := range rawParts {
		urlParts[i] = ParseURLPart(raw)
	}

	return urlParts
}