Repository navigation
Expand file tree
/
Copy pathdatabase.go
More file actions
74 lines (59 loc) · 1.7 KB
/
Copy pathdatabase.go
File metadata and controls
74 lines (59 loc) · 1.7 KB
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 main
import (
"database/sql"
"fmt"
"time"
_ "github.com/lib/pq"
)
const TimeFormat = "2006-01-02 15:04:05"
// DBConfig contains the necessary configuration for connecting to a database
type DBConfig struct {
Host string
Port string
User string
Password string // NB: Not particularly safe
DBName string
}
// GochatDB is a wrapper struct for easier expansion of the sql.DB struct
type GochatDB struct {
DB *sql.DB
}
// dbConnect connects to a database described by a database config.
// Returns error if unable to open and ping the database
func dbConnect(dbc DBConfig) (*GochatDB, error) {
connStr := fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmode=disable",
dbc.Host, dbc.Port, dbc.User, dbc.DBName)
if dbc.Password != "" {
connStr += "password=" + dbc.Password
}
db, err := sql.Open("postgres", connStr)
if err != nil {
return nil, err
}
err = db.Ping()
if err != nil {
return nil, err
}
return &GochatDB{DB: db}, nil
}
// LogConnection inserts a new connection into the database
func (gcdb *GochatDB) LogConnection(message Message) error {
cmd := `INSERT INTO users(username, remote_addr, registered) VALUES($1, $2, $3)`
_, err := gcdb.DB.Exec(cmd,
message.Sender.Username,
message.Sender.Conn.RemoteAddr().String(),
time.Now().Format(TimeFormat),
)
return err
}
// LogMessage inserts a new message from an existing connection into the databse
func (gcdb *GochatDB) LogMessage(message Message) error {
cmd := `INSERT INTO messages(message, sender, sender_addr, sent) VALUES($1, $2, $3, $4)`
_, err := gcdb.DB.Exec(cmd,
message.Text,
message.Sender.Username,
message.Sender.Conn.RemoteAddr().String(),
time.Now().Format(TimeFormat),
)
return err
}