Browse Source

Added db row creation function

main
Unbewohnte 3 years ago
parent
commit
f380c3d491
  1. 8
      dbHandle/create.go
  2. 1
      dbHandle/db.go
  3. 75
      dbHandle/handle.go
  4. 9
      main.go
  5. 22
      randomData/randomData.go

8
dbHandle/create.go

@ -2,6 +2,7 @@ package dbhandle
import ( import (
"database/sql" "database/sql"
"fmt"
"os" "os"
"path/filepath" "path/filepath"
@ -12,10 +13,10 @@ import (
var dbpath string var dbpath string
// Creates a local database file in the same directory // Creates a local database file in the same directory
// as executable if does not exist already. Creates a table "randomdata" with // as executable if does not exist already. Creates a table with
// such structure: (id PRIMARY KEY, title TEXT, text TEXT), which // such structure: (id PRIMARY KEY, title TEXT, text TEXT), which
// represents underlying fields of `RandomData` // represents underlying fields of `RandomData`
func CreateLocalDB(dbName string) (*DB, error) { func CreateLocalDB(dbName string, newTableName string) (*DB, error) {
// double check if dbName is actually just a name, not a path // double check if dbName is actually just a name, not a path
dbName = filepath.Base(dbName) dbName = filepath.Base(dbName)
@ -40,10 +41,11 @@ func CreateLocalDB(dbName string) (*DB, error) {
return nil, err return nil, err
} }
_, err = db.Exec("CREATE TABLE IF NOT EXISTS randomdata (id INTEGER PRIMARY KEY, title TEXT, text TEXT)") _, err = db.Exec(fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY, title TEXT, text TEXT)", newTableName))
if err != nil { if err != nil {
return nil, err return nil, err
} }
tableName = newTableName
return &DB{db}, nil return &DB{db}, nil
} }

1
dbHandle/db.go

@ -7,3 +7,4 @@ type DB struct {
} }
const drivername string = "sqlite3" const drivername string = "sqlite3"
var tableName string

75
dbHandle/handle.go

@ -1,6 +1,10 @@
package dbhandle package dbhandle
import ( import (
"encoding/json"
"fmt"
"io"
"log"
"net/http" "net/http"
randomdata "github.com/Unbewohnte/crud-api/randomData" randomdata "github.com/Unbewohnte/crud-api/randomData"
@ -8,7 +12,30 @@ import (
) )
func (db *DB) GetEverything() ([]*randomdata.RandomData, error) { func (db *DB) GetEverything() ([]*randomdata.RandomData, error) {
return nil, nil rows, err := db.Query(fmt.Sprintf("SELECT * FROM %s", tableName))
if err != nil {
return nil, err
}
var contents []*randomdata.RandomData
for rows.Next() {
var id uint
var title string
var text string
rows.Scan(&id, &title, &text)
var randomData = randomdata.RandomData{
ID: id,
Title: title,
Text: text,
}
fmt.Println(id, title, text)
contents = append(contents, &randomData)
}
return contents, nil
} }
func (db *DB) GetSpecific() (*randomdata.RandomData, error) { func (db *DB) GetSpecific() (*randomdata.RandomData, error) {
@ -24,7 +51,7 @@ func (db *DB) PatchSpecific() error {
} }
func (db *DB) Create(rd randomdata.RandomData) error { func (db *DB) Create(rd randomdata.RandomData) error {
_, err := db.Exec("INSERT INTO randomdata (title, text) VALUES (?, ?)", rd.Title, rd.Text) _, err := db.Exec(fmt.Sprintf("INSERT INTO %s (title, text) VALUES (?, ?)", tableName), rd.Title, rd.Text)
if err != nil { if err != nil {
return err return err
} }
@ -32,10 +59,50 @@ func (db *DB) Create(rd randomdata.RandomData) error {
return nil return nil
} }
func (db *DB) HandleSpecificWeb(w http.ResponseWriter, r *http.Request) { func (db *DB) HandleGlobalWeb(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
if r.Header.Get("content-type") != "application/json" {
w.WriteHeader(http.StatusUnsupportedMediaType)
return
}
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
var data randomdata.RandomData
err = json.Unmarshal(body, &data)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
err = db.Create(data)
if err != nil {
log.Printf("Could not create a row: %s", err)
}
w.WriteHeader(http.StatusAccepted)
case http.MethodGet:
data, err := db.GetEverything()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("Could not retrieve db contents: %s\n", err)
return
}
w.Write()
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
} }
func (db *DB) HandleGlobalWeb(w http.ResponseWriter, r *http.Request) { func (db *DB) HandleSpecificWeb(w http.ResponseWriter, r *http.Request) {
} }

9
main.go

@ -12,8 +12,9 @@ import (
) )
var ( var (
port *uint = flag.Uint("port", 8080, "Specifies a port on which the helping page will be served") port *uint = flag.Uint("port", 8080, "Specifies a port on which the helping page will be served")
dbname string = "database.db" dbname string = "database.db"
tableName = "randomdata"
) )
func init() { func init() {
@ -28,11 +29,11 @@ func init() {
func main() { func main() {
// create a local db file // create a local db file
db, err := dbhandle.CreateLocalDB(dbname) db, err := dbhandle.CreateLocalDB(dbname, tableName)
if err != nil { if err != nil {
log.Fatalf("error setting up a database: %s", err) log.Fatalf("error setting up a database: %s", err)
} }
log.Println("Created db") log.Printf("Created %s db\n", tableName)
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("/", helpPage) mux.HandleFunc("/", helpPage)

22
randomData/randomData.go

@ -2,27 +2,17 @@ package randomdata
import ( import (
"encoding/json" "encoding/json"
"time"
) )
// The `bridge` between input values and a record in db // The `bridge` between input values and a record in db
type RandomData struct { type RandomData struct {
DateCreated int64 DateCreated int64
LastUpdated int64 LastUpdated int64
ID uint
Title string `json:"title"` Title string `json:"title"`
Text string `json:"text"` Text string `json:"text"`
} }
// Create a new `RandomData`
func New(title string, text string) *RandomData {
return &RandomData{
DateCreated: time.Now().UTC().Unix(),
LastUpdated: time.Now().UTC().Unix(),
Title: title,
Text: text,
}
}
// Unmarshal `RandomData` from Json encoded bytes // Unmarshal `RandomData` from Json encoded bytes
func FromJson(jsonBytes []byte) (*RandomData, error) { func FromJson(jsonBytes []byte) (*RandomData, error) {
var randomData RandomData var randomData RandomData
@ -33,3 +23,13 @@ func FromJson(jsonBytes []byte) (*RandomData, error) {
return &randomData, nil return &randomData, nil
} }
// Convert struct to json bytes
func (rd *RandomData) ToJson() ([]byte, error) {
bytes, err := json.Marshal(rd)
if err != nil {
return nil, err
}
return bytes, nil
}

Loading…
Cancel
Save