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:
2020-08-30 07:16:50 +02:00
parent cf4274c1e1
commit daa79b27ca
6 changed files with 137 additions and 3 deletions

33
models/db.go Normal file
View 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
View 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
}