-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse_url.go
47 lines (43 loc) · 1.32 KB
/
parse_url.go
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
package jsonnet
import (
"errors"
"fmt"
"net/url"
"github.com/google/go-jsonnet"
"github.com/google/go-jsonnet/ast"
)
// ParseURL returns a jsonnet function parseUrl which returns a dictionary representing the input url
func ParseURL() *jsonnet.NativeFunction {
return &jsonnet.NativeFunction{
Name: "parseUrl",
Params: ast.Identifiers{"url"},
Func: func(dataString []any) (res any, err error) {
if len(dataString) != 1 {
return nil, fmt.Errorf("bad arguments to parseUrl: needs %d argument", 1)
}
data, ok := dataString[0].(string)
if !ok {
return nil, errors.New("parseUrl failed to read input")
}
parsedSegments := map[string]any{}
parsedURL, err := url.Parse(data)
if err != nil {
return nil, fmt.Errorf("unable to parseUrl: %s", err)
}
parsedSegments["scheme"] = parsedURL.Scheme
parsedSegments["host"] = parsedURL.Host
parsedSegments["hostname"] = parsedURL.Hostname()
parsedSegments["port"] = parsedURL.Port()
parsedSegments["opaque"] = parsedURL.Opaque
parsedSegments["path"] = parsedURL.Path
parsedSegments["query"] = parsedURL.RawQuery
parsedSegments["fragment"] = parsedURL.Fragment
if parsedURL.User != nil {
parsedSegments["userinfo"] = parsedURL.User.String()
} else {
parsedSegments["userinfo"] = ""
}
return parsedSegments, nil
},
}
}