Extend this program:
- add a database for devices - read devices from database and present this data on a simple web/REST interface The code or model is from a blog entry from Alex Edward: https://www.alexedwards.net/blog/organising-database-access
This commit is contained in:
33
models/db.go
Normal file
33
models/db.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
type Datastore interface {
|
||||
AllDevices() ([]*Device, error)
|
||||
}
|
||||
|
||||
type DB struct {
|
||||
*sql.DB
|
||||
}
|
||||
|
||||
func NewDB(dataSourceName string) (*DB, error) {
|
||||
db, err := sql.Open("sqlite3", dataSourceName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = db.Ping(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sqlStmt := "CREATE TABLE IF NOT EXISTS devices (id TEXT not null primary key, mac TEXT, sn TEXT, lastMsg TEXT);"
|
||||
_, err = db.Exec(sqlStmt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &DB{db}, nil
|
||||
}
|
36
models/devices.go
Normal file
36
models/devices.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package models
|
||||
|
||||
type Device struct {
|
||||
ID string
|
||||
MAC string
|
||||
SN string
|
||||
LastMsg string
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
func (db *DB) AllDevices() ([]*Device, error) {
|
||||
rows, err := db.Query("SELECT * FROM devices")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
devices := make([]*Device, 0)
|
||||
for rows.Next() {
|
||||
device := new(Device)
|
||||
err := rows.Scan(&device.ID, &device.MAC, &device.SN, &device.LastMsg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
devices = append(devices, device)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return devices, nil
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user