-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.go
87 lines (76 loc) · 1.71 KB
/
user.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
79
80
81
82
83
84
85
86
87
package main
import (
"database/sql"
"time"
"github.com/jmoiron/sqlx"
log "github.com/sirupsen/logrus"
)
type User struct {
ID uint
UserName string `db:"user_name"`
PasswordHash string `db:"password_hash"`
CreatedAt time.Time `db:"created_at"`
}
type UserDao struct {
db *sqlx.DB
}
func NewUserDao(db *sqlx.DB) *UserDao {
return &UserDao{db: db}
}
type UserService interface {
CreateUserTable()
CreateUser(u User)
GetUsers() []*User
FindByUsername(userName string) (*User, error)
}
func (ud *UserDao) CreateUserTable() {
createSQL := `
CREATE TABLE if not exists users (
id INTEGER PRIMARY KEY,
user_name TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`
ud.db.MustExec(createSQL)
}
func (ud *UserDao) CreateUser(u User) {
const insertSQL = `
INSERT into users (user_name, password_hash)
VALUES (LOWER($1), $2)
`
ud.db.MustExec(insertSQL, u.UserName, u.PasswordHash)
}
func (ud *UserDao) FindByUsername(userName string) (*User, error) {
const userSQL = `
SELECT ID, user_name, password_hash, created_at
FROM users
WHERE user_name=$1
LIMIT 1
`
var user User
err := ud.db.Get(&user, userSQL, userName)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
return &user, nil
}
func (ud *UserDao) GetUsers() []*User {
const userSQL = `
SELECT user_name
FROM users
`
var users []*User
err := ud.db.Select(&users, userSQL)
if err != nil {
if err == sql.ErrNoRows {
return nil
}
log.Fatal(err)
}
return users
}