diff --git a/main.go b/main.go index f2b294d..05c53d5 100644 --- a/main.go +++ b/main.go @@ -2,37 +2,68 @@ package main import ( "net/http" - "fmt" + //"fmt" "encoding/json" + "database/sql" + "time" + _ "github.com/mattn/go-sqlite3" "log" ) var messages []*string +var db *sql.DB func main() { + dbo, err := sql.Open("sqlite3", "content") + if err != nil { + log.Fatal("couldn’t open database. exiting...") + return + } else { + db = dbo + } //listener, err = net.Listen("socket", "/tmp/ http.HandleFunc("/", get) http.HandleFunc("/add", post) log.Fatal(http.ListenAndServe(":12345", nil)) } +func writeToDB(post BlogPost) { + stmt, _ := db.Prepare("INSERT INTO blogposts(author, title, content, date) VALUES (?, ?, ?, ?)") + stmt.Exec(post.Author, post.Title, post.Content, time.Now().Format("2006-01-02")) +} + type BlogPost struct { - Message string `"message"` + Content string `"content"` Title string `"title"` + Author string `"author"` Secret string `"secret"` } func get(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - w.Write([]byte("response:")) - for _, m := range messages { - w.Write([]byte(*m)) + w.Write([]byte("response:\n")) + //stmt, _ := db.Prepare("SELECT content from blogposts") + //res, _ := stmt.Exec() + res, _ := db.Query("SELECT content from blogposts") + for _, e := range(resultToStrings(res)) { + w.Write([]byte(e + "\n")) } } func post(w http.ResponseWriter, r *http.Request) { var post BlogPost json.NewDecoder(r.Body).Decode(&post) - fmt.Println(post.Message) - messages = append(messages, &post.Message) + messages = append(messages, &post.Content) + writeToDB(post) +} + +func resultToStrings(res *sql.Rows) []string { + defer res.Close() + entries := make([]string, 0) + for res.Next() { + var e string + res.Scan(&e) + entries = append(entries, e) + } + return entries } diff --git a/notes b/notes index ea2c811..143de00 100644 --- a/notes +++ b/notes @@ -1,4 +1,4 @@ -curl localhost:12345/add -d '{"message": "a message", "Title": "title", "Secret": "asdawdwd"}' -H 'Content-Type: application/json' -v +curl localhost:12345/add -d '{"content": "a message", "Title": "title", "Secret": "asdawdwd", "author": "me"}' -H 'Content-Type: application/json' -v for sqlite3 CGO_ENABLED=1