-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathuser.go
69 lines (56 loc) · 1.85 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
package models
import (
"database/sql"
"fmt"
"log"
"golang.org/x/crypto/bcrypt"
"gopkg.in/gorp.v1"
_ "github.com/go-sql-driver/mysql"
"github.com/golang/glog"
)
type User struct {
Id int64 `db:"UserId"`
Email string
Username string
Password []byte
}
func (user *User) HashPassword(password string) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
glog.Fatalf("Couldn't hash password: %v", err)
panic(err)
}
user.Password = hash
}
func GetUserByEmail(dbMap *gorp.DbMap, email string) (user *User) {
err := dbMap.SelectOne(&user, "SELECT * FROM Users where Email = ?", email)
if err != nil {
glog.Warningf("Can't get user by email: %v", err)
}
return
}
func InsertUser(dbMap *gorp.DbMap, user *User) error {
return dbMap.Insert(user)
}
func GetDbMap(user, password, hostname, port, database string) *gorp.DbMap {
// connect to db using standard Go database/sql API
// use whatever database/sql driver you wish
//TODO: Get user, password and database from config.
db, err := sql.Open("mysql", fmt.Sprint(user, ":", password, "@(", hostname, ":", port, ")/", database, "?charset=utf8mb4"))
checkErr(err, "sql.Open failed")
// construct a gorp DbMap
dbMap := &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{Engine: "InnoDB", Encoding: "UTF8MB4"}}
// add a table, setting the table name to 'posts' and
// specifying that the Id property is an auto incrementing PK
dbMap.AddTableWithName(User{}, "Users").SetKeys(true, "Id")
// create the table. in a production system you'd generally
// use a migration tool, or create the tables via scripts
err = dbMap.CreateTablesIfNotExists()
checkErr(err, "Create tables failed")
return dbMap
}
func checkErr(err error, msg string) {
if err != nil {
log.Fatalln(msg, err)
}
}