Debian Codegraph @

go/pkg/amqp/url.go

raw
1 /*
2 Licensed to the Apache Software Foundation (ASF) under one
3 or more contributor license agreements. See the NOTICE file
4 distributed with this work for additional information
5 regarding copyright ownership. The ASF licenses this file
6 to you under the Apache License, Version 2.0 (the
7 "License"); you may not use this file except in compliance
8 with the License. You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing,
13 software distributed under the License is distributed on an
14 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 KIND, either express or implied. See the License for the
16 specific language governing permissions and limitations
17 under the License.
18 */
19
20 package amqp
21
22 import (
23 "errors"
24 "net"
25 "net/url"
26 "strings"
27 )
28
29 const (
30 amqp string = "amqp"
31 amqps = "amqps"
32 defaulthost = "localhost"
33 )
34
35 // The way this is used it can only get a hostport already validated by
36 // the URL parser, so this means we can skip some error checks
37 func splitHostPort(hostport string) (string, string, error) {
38 if hostport == "" {
39 return "", "", nil
40 }
41 if hostport[0] == '[' {
42 // There must be a matching ']' as already validated
43 if l := strings.LastIndex(hostport, "]"); len(hostport) == l+1 {
44 // trim off '[' and ']'
45 return hostport[1:l], "", nil
46 }
47 } else if strings.IndexByte(hostport, ':') < 0 {
48 return hostport, "", nil
49 }
50 return net.SplitHostPort(hostport)
51 }
52
53 func UpdateURL(in *url.URL) (err error) {
54 // Detect form without "amqp://" and stick it on front
55 // to make it match the usual proton defaults
56 u := new (url.URL)
57 *u = *in
58 if (u.Scheme != "" && u.Opaque != "") ||
59 (u.Scheme == "" && u.Host == "") {
60 input := u.String()
61 input = "amqp://" + input
62 u, err = url.Parse(input)
63 if err != nil {
64 return
65 }
66 }
67 // If Scheme is still "" then default to amqp
68 if u.Scheme == "" {
69 u.Scheme = amqp
70 }
71 // Error if the scheme is not an amqp scheme
72 if u.Scheme != amqp && u.Scheme != amqps {
73 return errors.New("invalid amqp scheme")
74 }
75 // Decompose Host into host and port
76 host, port, err := splitHostPort(u.Host)
77 if err != nil {
78 return
79 }
80 if host == "" {
81 host = defaulthost
82 }
83 if port == "" {
84 port = u.Scheme
85 }
86 u.Host = net.JoinHostPort(host, port)
87 *in = *u
88 return nil
89 }
90
91 // ParseUrl parses an AMQP URL string and returns a net/url.Url.
92 //
93 // It is more forgiving than net/url.Parse and allows most of the parts of the
94 // URL to be missing, assuming AMQP defaults.
95 //
96 func ParseURL(s string) (u *url.URL, err error) {
97 if u, err = url.Parse(s); err != nil {
98 return
99 }
100 if err = UpdateURL(u); err != nil {
101 u = nil
102 }
103 return u, err
104 }