Debian Codegraph @

pkg/format/urlpart.go

raw
1 //go:generate stringer -type=URLPart -trimprefix URL
2
3 package format
4
5 import (
6 "log"
7 "strconv"
8 "strings"
9 )
10
11 // URLPart is an indicator as to what part of an URL a field is serialized to.
12 type URLPart int
13
14 // indicator as to what part of an URL a field is serialized to.
15 const (
16 URLQuery URLPart = iota
17 URLUser
18 URLPassword
19 URLHost
20 URLPort
21 URLPath // Base path; additional paths are URLPath + N
22 )
23
24 // Suffix returns the separator between the URLPart and its subsequent part.
25 func (u URLPart) Suffix() rune {
26 switch u {
27 case URLQuery:
28 return '/'
29 case URLUser:
30 return ':'
31 case URLPassword:
32 return '@'
33 case URLHost:
34 return ':'
35 case URLPort:
36 return '/'
37 case URLPath:
38 return '/'
39 default:
40 return '/'
41 }
42 }
43
44 // ParseURLPart returns the URLPart that matches the supplied string.
45 func ParseURLPart(inputString string) URLPart {
46 lowerString := strings.ToLower(inputString)
47 switch lowerString {
48 case "user":
49 return URLUser
50 case "pass", "password":
51 return URLPassword
52 case "host":
53 return URLHost
54 case "port":
55 return URLPort
56 case "path", "path1":
57 return URLPath
58 case "query", "":
59 return URLQuery
60 }
61
62 // Handle dynamic path segments (e.g., "path2", "path3", etc.).
63 if strings.HasPrefix(lowerString, "path") && len(lowerString) > 4 {
64 if num, err := strconv.Atoi(lowerString[4:]); err == nil && num >= 2 {
65 return URLPath + URLPart(num-1) // Offset from URLPath; "path2" -> URLPath+1
66 }
67 }
68
69 log.Printf("invalid URLPart: %s, defaulting to URLQuery", lowerString)
70
71 return URLQuery
72 }
73
74 // ParseURLParts returns the URLParts that matches the supplied string.
75 func ParseURLParts(s string) []URLPart {
76 rawParts := strings.Split(s, ",")
77 urlParts := make([]URLPart, len(rawParts))
78
79 for i, raw := range rawParts {
80 urlParts[i] = ParseURLPart(raw)
81 }
82
83 return urlParts
84 }