From f380c3d491b655c92a0326a1512ffb485280a6ea Mon Sep 17 00:00:00 2001 From: Unbewohnte Date: Mon, 20 Sep 2021 22:12:21 +0300 Subject: [PATCH] Added db row creation function --- dbHandle/create.go | 8 +++-- dbHandle/db.go | 1 + dbHandle/handle.go | 75 +++++++++++++++++++++++++++++++++++++--- main.go | 9 ++--- randomData/randomData.go | 22 ++++++------ 5 files changed, 93 insertions(+), 22 deletions(-) diff --git a/dbHandle/create.go b/dbHandle/create.go index 7661d85..f17c8ff 100644 --- a/dbHandle/create.go +++ b/dbHandle/create.go @@ -2,6 +2,7 @@ package dbhandle import ( "database/sql" + "fmt" "os" "path/filepath" @@ -12,10 +13,10 @@ import ( var dbpath string // 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 // 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 dbName = filepath.Base(dbName) @@ -40,10 +41,11 @@ func CreateLocalDB(dbName string) (*DB, error) { 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 { return nil, err } + tableName = newTableName return &DB{db}, nil } diff --git a/dbHandle/db.go b/dbHandle/db.go index 84ae967..3c69fdc 100644 --- a/dbHandle/db.go +++ b/dbHandle/db.go @@ -7,3 +7,4 @@ type DB struct { } const drivername string = "sqlite3" +var tableName string diff --git a/dbHandle/handle.go b/dbHandle/handle.go index ae9d41e..909e5af 100644 --- a/dbHandle/handle.go +++ b/dbHandle/handle.go @@ -1,6 +1,10 @@ package dbhandle import ( + "encoding/json" + "fmt" + "io" + "log" "net/http" randomdata "github.com/Unbewohnte/crud-api/randomData" @@ -8,7 +12,30 @@ import ( ) 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) { @@ -24,7 +51,7 @@ func (db *DB) PatchSpecific() 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 { return err } @@ -32,10 +59,50 @@ func (db *DB) Create(rd randomdata.RandomData) error { 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) { } diff --git a/main.go b/main.go index 53e1cb2..e0a7224 100644 --- a/main.go +++ b/main.go @@ -12,8 +12,9 @@ import ( ) var ( - port *uint = flag.Uint("port", 8080, "Specifies a port on which the helping page will be served") - dbname string = "database.db" + port *uint = flag.Uint("port", 8080, "Specifies a port on which the helping page will be served") + dbname string = "database.db" + tableName = "randomdata" ) func init() { @@ -28,11 +29,11 @@ func init() { func main() { // create a local db file - db, err := dbhandle.CreateLocalDB(dbname) + db, err := dbhandle.CreateLocalDB(dbname, tableName) if err != nil { log.Fatalf("error setting up a database: %s", err) } - log.Println("Created db") + log.Printf("Created %s db\n", tableName) mux := http.NewServeMux() mux.HandleFunc("/", helpPage) diff --git a/randomData/randomData.go b/randomData/randomData.go index ed921bf..0464e79 100644 --- a/randomData/randomData.go +++ b/randomData/randomData.go @@ -2,27 +2,17 @@ package randomdata import ( "encoding/json" - "time" ) // The `bridge` between input values and a record in db type RandomData struct { DateCreated int64 LastUpdated int64 + ID uint Title string `json:"title"` 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 func FromJson(jsonBytes []byte) (*RandomData, error) { var randomData RandomData @@ -33,3 +23,13 @@ func FromJson(jsonBytes []byte) (*RandomData, error) { 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 +}