url-parser/command/commands.go

110 lines
2.1 KiB
Go
Raw Permalink Normal View History

2020-09-21 18:24:51 +00:00
package command
2020-02-02 23:05:18 +00:00
import (
"net/url"
"strings"
2023-12-06 08:14:10 +00:00
"github.com/rs/zerolog/log"
"github.com/thegeeklab/url-parser/config"
2020-02-02 23:05:18 +00:00
)
type QueryParam struct {
Key string `json:"key"`
Value string `json:"value"`
}
type URL struct {
url *url.URL
Scheme string `json:"scheme"`
Hostname string `json:"hostname"`
Port string `json:"port"`
Path string `json:"path"`
Fragment string `json:"fragment"`
RawQuery string `json:"rawQuery"`
Query string `json:"-"`
QueryParams []QueryParam `json:"queryParams"`
Username string `json:"username"`
Password string `json:"password"`
}
2020-02-02 23:05:18 +00:00
func (u *URL) String() string {
return u.url.String()
}
type Parser struct {
URL string
QueryField string
QuerySplit bool
}
func NewURLParser(url, queryField string, querySplit bool) *Parser {
return &Parser{
URL: url,
QueryField: queryField,
QuerySplit: querySplit,
}
}
func (p *Parser) parse() *URL {
urlString := strings.TrimSpace(p.URL)
parts, err := url.Parse(urlString)
2020-02-02 23:05:18 +00:00
if err != nil {
2023-12-06 08:14:10 +00:00
log.Fatal().Err(err).Msg(config.ErrParseURL.Error())
2020-02-02 23:05:18 +00:00
}
extURL := &URL{
url: parts,
Scheme: parts.Scheme,
Hostname: parts.Hostname(),
Path: parts.Path,
Fragment: parts.Fragment,
QueryParams: []QueryParam{},
}
if len(parts.Scheme) > 0 {
extURL.Hostname = parts.Hostname()
extURL.Port = parts.Port()
}
if parts.User != nil {
if len(parts.User.Username()) > 0 {
extURL.Username = parts.User.Username()
}
}
if parts.User != nil {
pw, _ := parts.User.Password()
if len(pw) > 0 {
extURL.Password = pw
}
}
// Handle query field extraction
if parts.RawQuery != "" {
extURL.RawQuery = parts.RawQuery
}
if p.QueryField != "" {
if result := parts.Query().Get(p.QueryField); result != "" {
extURL.Query = result
}
} else {
extURL.Query = parts.RawQuery
}
// Handle query parameter splitting
values := parts.Query()
for k, v := range values {
if len(v) > 0 {
extURL.QueryParams = append(extURL.QueryParams, QueryParam{
Key: k,
Value: v[0],
})
}
}
return extURL
2020-02-02 23:05:18 +00:00
}