-
Notifications
You must be signed in to change notification settings - Fork 0
/
utm.go
78 lines (63 loc) · 1.77 KB
/
utm.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package utm
import (
"errors"
"net/url"
)
// Config is used to configure UTM tags for a URL
type Config struct {
Source string
Medium string
Campaign string
Content string
Term string
}
var (
// ErrURLRequired is thrown when the URL passed is empty
ErrURLRequired = errors.New("A URL is required")
// ErrInvalidURL is thrown when the passed URL doesn't validate
ErrInvalidURL = errors.New("The URL is invalid")
// ErrSourceRequired is thrown when no source is passed
ErrSourceRequired = errors.New("A Source is required")
// ErrMediumRequired is thrown when no source is passed
ErrMediumRequired = errors.New("A Medium is required")
// ErrCampaignRequired is thrown when no campaign is passed
ErrCampaignRequired = errors.New("A Campaign is required")
)
// BuildURL adds UTM tags to the passed URL
func BuildURL(rawurl string, config Config) (string, error) {
if rawurl == "" {
return "", ErrURLRequired
}
if config.Source == "" {
return "", ErrSourceRequired
}
if config.Medium == "" {
return "", ErrMediumRequired
}
if config.Campaign == "" {
return "", ErrCampaignRequired
}
// First parse the URL
url, err := url.Parse(rawurl)
if err != nil {
return "", ErrInvalidURL
}
// UTM builder can only be used on http and https schemes, so lets check those
if url.Scheme != "http" && url.Scheme != "https" {
return "", ErrInvalidURL
}
// Now add any new params to the query string
query := url.Query()
query.Add("utm_source", config.Source)
query.Add("utm_medium", config.Medium)
query.Add("utm_campaign", config.Campaign)
if config.Content != "" {
query.Add("utm_content", config.Content)
}
if config.Term != "" {
query.Add("utm_term", config.Term)
}
//Reassign the query back
url.RawQuery = query.Encode()
return url.String(), nil
}