70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"net/http"
|
|
//"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 {
|
|
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:\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)
|
|
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
|
|
}
|