2015-01-08 02:00:00 -06:00
|
|
|
package util
|
2014-10-03 02:03:16 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/url"
|
2014-12-29 06:35:51 -06:00
|
|
|
"strings"
|
2014-10-03 02:03:16 -05:00
|
|
|
)
|
|
|
|
|
2019-10-07 07:18:14 -05:00
|
|
|
// URLQueryReader is a ApiURL query type.
|
2019-01-28 15:18:48 -06:00
|
|
|
type URLQueryReader struct {
|
2014-10-03 02:03:16 -05:00
|
|
|
values url.Values
|
|
|
|
}
|
|
|
|
|
2019-01-28 15:18:48 -06:00
|
|
|
// NewURLQueryReader parses a raw query and returns it as a URLQueryReader type.
|
|
|
|
func NewURLQueryReader(urlInfo *url.URL) (*URLQueryReader, error) {
|
2018-08-05 15:54:06 -05:00
|
|
|
u, err := url.ParseQuery(urlInfo.RawQuery)
|
2017-11-28 08:20:22 -06:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2014-10-03 02:03:16 -05:00
|
|
|
}
|
2017-11-28 08:20:22 -06:00
|
|
|
|
2019-01-28 15:18:48 -06:00
|
|
|
return &URLQueryReader{
|
2017-11-28 08:20:22 -06:00
|
|
|
values: u,
|
|
|
|
}, nil
|
2014-10-03 02:03:16 -05:00
|
|
|
}
|
|
|
|
|
2019-10-07 07:18:14 -05:00
|
|
|
// Get parse parameters from an ApiURL. If the parameter does not exist, it returns
|
2019-01-28 15:09:40 -06:00
|
|
|
// the default value.
|
2019-01-28 15:18:48 -06:00
|
|
|
func (r *URLQueryReader) Get(name string, def string) string {
|
2014-10-03 02:03:16 -05:00
|
|
|
val := r.values[name]
|
|
|
|
if len(val) == 0 {
|
|
|
|
return def
|
|
|
|
}
|
|
|
|
|
|
|
|
return val[0]
|
|
|
|
}
|
2014-12-29 06:35:51 -06:00
|
|
|
|
2019-10-07 07:18:14 -05:00
|
|
|
// JoinURLFragments joins two ApiURL fragments into only one ApiURL string.
|
2019-01-28 15:18:48 -06:00
|
|
|
func JoinURLFragments(a, b string) string {
|
2014-12-29 06:35:51 -06:00
|
|
|
aslash := strings.HasSuffix(a, "/")
|
|
|
|
bslash := strings.HasPrefix(b, "/")
|
2016-01-29 11:31:00 -06:00
|
|
|
|
|
|
|
if len(b) == 0 {
|
|
|
|
return a
|
|
|
|
}
|
|
|
|
|
2014-12-29 06:35:51 -06:00
|
|
|
switch {
|
|
|
|
case aslash && bslash:
|
|
|
|
return a + b[1:]
|
|
|
|
case !aslash && !bslash:
|
|
|
|
return a + "/" + b
|
|
|
|
}
|
|
|
|
return a + b
|
|
|
|
}
|