summaryrefslogtreecommitdiff
path: root/environment/environment.go
blob: a4ae71937b5cbf099a7ceb7fc624af4a39a6e08c (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
// Package environment provides the Env type for commonly used data in the application.
package environment

import (
	"database/sql"

	_ "github.com/go-sql-driver/mysql"

	"code.laria.me/laria.me/config"
)

// Env provides commonly used data in the application
type Env struct {
	configPath string

	config *config.Config
	db     *sql.DB
}

func New(configPath string) *Env {
	return &Env{
		configPath: configPath,
	}
}

func (e *Env) Config() (*config.Config, error) {
	if e.config != nil {
		return e.config, nil
	}

	conf, err := config.LoadConfig(e.configPath)
	if err != nil {
		return nil, err
	}

	e.config = conf
	return conf, nil
}

func (e *Env) DB() (*sql.DB, error) {
	if e.db != nil {
		return e.db, nil
	}

	conf, err := e.Config()
	if err != nil {
		return nil, err
	}

	var db *sql.DB
	db, err = sql.Open("mysql", conf.DbDsn)
	if err != nil {
		return nil, err
	}

	e.db = db
	return db, nil
}