Backend can now send and receive posts

This commit is contained in:
kageru 2018-11-04 13:22:36 +01:00
parent 436367a667
commit a2e3f7c845
2 changed files with 39 additions and 8 deletions

45
main.go
View File

@ -2,37 +2,68 @@ package main
import ( import (
"net/http" "net/http"
"fmt" //"fmt"
"encoding/json" "encoding/json"
"database/sql"
"time"
_ "github.com/mattn/go-sqlite3"
"log" "log"
) )
var messages []*string var messages []*string
var db *sql.DB
func main() { 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/ //listener, err = net.Listen("socket", "/tmp/
http.HandleFunc("/", get) http.HandleFunc("/", get)
http.HandleFunc("/add", post) http.HandleFunc("/add", post)
log.Fatal(http.ListenAndServe(":12345", nil)) 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 { type BlogPost struct {
Message string `"message"` Content string `"content"`
Title string `"title"` Title string `"title"`
Author string `"author"`
Secret string `"secret"` Secret string `"secret"`
} }
func get(w http.ResponseWriter, r *http.Request) { func get(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
w.Write([]byte("response:")) w.Write([]byte("response:\n"))
for _, m := range messages { //stmt, _ := db.Prepare("SELECT content from blogposts")
w.Write([]byte(*m)) //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) { func post(w http.ResponseWriter, r *http.Request) {
var post BlogPost var post BlogPost
json.NewDecoder(r.Body).Decode(&post) json.NewDecoder(r.Body).Decode(&post)
fmt.Println(post.Message) messages = append(messages, &post.Content)
messages = append(messages, &post.Message) 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
} }

2
notes
View File

@ -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 for sqlite3
CGO_ENABLED=1 CGO_ENABLED=1