fathom/models/visitor.go

61 lines
1.2 KiB
Go
Raw Normal View History

package models
import (
2016-12-11 13:50:01 +00:00
"crypto/md5"
"database/sql"
"encoding/hex"
)
type Visitor struct {
2016-12-11 13:50:01 +00:00
ID int64
Key string
BrowserName string
BrowserVersion string
BrowserLanguage string
Country string
DeviceOS string
IpAddress string
ScreenResolution string
}
func (v *Visitor) Save(conn *sql.DB) error {
2016-12-11 13:50:01 +00:00
// prepare statement for inserting data
stmt, err := conn.Prepare(`INSERT INTO visitors (
visitor_key,
ip_address,
device_os,
browser_name,
browser_version,
browser_language,
screen_resolution,
country
) VALUES( ?, ?, ?, ?, ?, ?, ?, ? )`)
2016-12-11 13:50:01 +00:00
if err != nil {
return err
}
defer stmt.Close()
2016-12-11 13:50:01 +00:00
result, err := stmt.Exec(
v.Key,
v.IpAddress,
v.DeviceOS,
v.BrowserName,
v.BrowserVersion,
v.BrowserLanguage,
v.ScreenResolution,
v.Country,
)
if err != nil {
return err
}
2016-12-11 13:50:01 +00:00
v.ID, err = result.LastInsertId()
return err
}
2016-12-10 14:58:54 +00:00
2016-12-11 13:50:01 +00:00
// GenerateKey generates the "unique" visitor key
func (v *Visitor) GenerateKey() string {
byteKey := md5.Sum([]byte(v.IpAddress + v.DeviceOS + v.BrowserName + v.ScreenResolution))
return hex.EncodeToString(byteKey[:])
}