summaryrefslogtreecommitdiff
path: root/internal/url/addr.go
blob: e69d200b60db452fb6bab3a09f4b559bb3ea86d0 (plain)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package url

import (
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"time"
)

type Websites_t []string

type UserParams struct {
	Websites Websites_t    `json:"websites"`
	Timeout  time.Duration `json:"timeout"`
	Retry    int8          `json:"retry"`
}

type options struct {
	websites Websites_t
	timeout  time.Duration
	retry    int8
}

func NewUserParams(opts ...func(*options)) *UserParams {
	// will fail on default, but allows for just setting
	// websites field without worrying about other opts
	o := options{
		websites: nil,
		timeout:  1 * time.Hour,
		retry:    5,
	}

	for _, opt := range opts {
		opt(&o)
	}

	return &UserParams{
		Websites: o.websites,
		Timeout:  o.timeout,
		Retry:    o.retry,
	}
}

func WithWebsites(w Websites_t) func(*options) {
	return func(o *options) {
		o.websites = w
	}
}

func WithTimeout(t time.Duration) func(*options) {
	return func(o *options) {
		o.timeout = t
	}
}

func WithRetry(r int8) func(*options) {
	return func(o *options) {
		o.retry = r
	}
}

func (u *UserParams) NewWebsite(w string) (*Websites_t, error) {
	if !strings.HasPrefix(w, "http://") || !strings.HasPrefix(w, "https://") {
		return &(*u).Websites, errors.New("url entered is not an http or https url")
	}

	u.Websites[len((*u).Websites)] = w

	return &(*u).Websites, nil
}

func (u *UserParams) GetWebsites() (*Websites_t, error) {
	if (*u).Websites == nil {
		return nil, errors.New("no websites given in user params")
	}

	return &(*u).Websites, nil
}

func (u *UserParams) Package() ([]byte, error) {
	// turn struct values into json byte array for child proc
	if u == nil {
		return nil, errors.New("package: userparams is not initialized")
	} else if (*u).Websites == nil {
		return nil, errors.New("package: websites empty")
	}

	packed, err := json.Marshal(u)
	if err != nil {
		return nil, err
	}

	return packed, nil
}

// TODO: deconstruct opts into a string for relay to chld proc cmd
func (u *UserParams) DeconstructOpts() (string, error) {
	if (*u).Retry == 0 || (*u).Timeout == 0 || (*u).Websites == nil {
		return "", errors.New("deconstructopts: one or more options are nil")
	}
	return fmt.Sprintf("websites=[],timeout=%v,retry=%d", (*u).Timeout, (*u).Retry), nil
}