-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
74 lines (58 loc) · 1.66 KB
/
config.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
package short
import (
"net/url"
"strings"
"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"
)
// Config is used to customize the shortener.
// To create a config instance use `DefaultConfig()`.
type Config interface {
getConfig() *config
// WithHost sets the hosts of the shortened url.
// E.g. if host is `my.url`` the shortened url could be `https://my.url/eRt35df`.
WithHost(host string) Config
// WithMongo sets the URI for connecting to Mongo.
// https://www.mongodb.com/docs/manual/reference/connection-string/
// Example: `mongodb://root:password123@198.174.21.23:27017/databasename`
WithMongoUri(mongoUri string) Config
}
type config struct {
host string
mongoUri string
err error
}
// DefaultConfig returns a configuration with default values.
// default host: `localhost:8080`.
// default mongo URI: `mongodb://localhost:27017`.
func DefaultConfig() Config {
var c config
c.host = "localhost:8080"
c.mongoUri = "mongodb://localhost:27017"
return &c
}
func (c *config) getConfig() *config {
return c
}
// WithHost set the short link host.
func (c config) WithHost(host string) Config {
if !strings.HasPrefix(host, "https://") && !strings.HasPrefix(host, "http://") {
host = "https://" + host
}
u, err := url.ParseRequestURI(host)
if err != nil {
c.err = err
} else {
c.host = u.Host
}
return &c
}
// WithMongoUri set the URI for connecting to MongoDB.
// If the MongoUri does not contain a database name, the database name will default to `short`.
func (c config) WithMongoUri(mongoUri string) Config {
if _, err := connstring.ParseAndValidate(mongoUri); err != nil {
c.err = err
} else {
c.mongoUri = mongoUri
}
return &c
}