hatecomputers.club/database/dns.go

75 lines
1.9 KiB
Go

package database
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
"log"
"time"
)
type DNSRecord struct {
ID string `json:"id"`
UserID string `json:"user_id"`
Name string `json:"name"`
Type string `json:"type"`
Content string `json:"content"`
TTL int `json:"ttl"`
CreatedAt time.Time `json:"created_at"`
}
func GetUserDNSRecords(db *sql.DB, userID string) ([]DNSRecord, error) {
log.Println("getting dns records for user", userID)
rows, err := db.Query("SELECT * FROM dns_records WHERE user_id = ?", userID)
if err != nil {
return nil, err
}
defer rows.Close()
var records []DNSRecord
for rows.Next() {
var record DNSRecord
err := rows.Scan(&record.ID, &record.UserID, &record.Name, &record.Type, &record.Content, &record.TTL, &record.CreatedAt)
if err != nil {
return nil, err
}
records = append(records, record)
}
return records, nil
}
func SaveDNSRecord(db *sql.DB, record *DNSRecord) (*DNSRecord, error) {
log.Println("saving dns record", record)
record.CreatedAt = time.Now()
_, err := db.Exec("INSERT OR REPLACE INTO dns_records (id, user_id, name, type, content, ttl, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)", record.ID, record.UserID, record.Name, record.Type, record.Content, record.TTL, record.CreatedAt)
if err != nil {
return nil, err
}
return record, nil
}
func GetDNSRecord(db *sql.DB, recordID string) (*DNSRecord, error) {
log.Println("getting dns record", recordID)
row := db.QueryRow("SELECT * FROM dns_records WHERE id = ?", recordID)
var record DNSRecord
err := row.Scan(&record.ID, &record.UserID, &record.Name, &record.Type, &record.Content, &record.TTL, &record.CreatedAt)
if err != nil {
return nil, err
}
return &record, nil
}
func DeleteDNSRecord(db *sql.DB, recordID string) error {
log.Println("deleting dns record", recordID)
_, err := db.Exec("DELETE FROM dns_records WHERE id = ?", recordID)
if err != nil {
return err
}
return nil
}