goblog/server.go

67 lines
1.5 KiB
Go
Raw Permalink Normal View History

package main
import (
"net/http"
"encoding/json"
"log"
"encoding/hex"
"crypto/sha512"
"io"
2018-11-04 19:58:34 +01:00
"html/template"
)
2018-11-04 19:58:34 +01:00
type OutputFormatter struct {
Author string
Content string
}
type Blog struct {
Posts []BlogPost
2018-11-04 19:58:34 +01:00
}
func startServer() {
http.HandleFunc("/", get)
http.HandleFunc("/add", post)
log.Fatal(http.ListenAndServe(":12345", nil))
}
func get(w http.ResponseWriter, r *http.Request) {
2018-11-04 21:13:04 +01:00
t, err := template.ParseFiles("templates/overview.html")
2018-11-04 19:58:34 +01:00
if err != nil {
log.Panic(err)
}
w.WriteHeader(http.StatusOK)
2018-11-04 19:58:34 +01:00
/*
w.Write([]byte("response:\n"))
for _, post := range readBlogpostsFromDB() {
w.Write([]byte(post.Content))
}
2018-11-04 19:58:34 +01:00
*/
2018-11-04 21:13:04 +01:00
results := readBlogpostsFromDB()
t.ExecuteTemplate(w, "overview.html", Blog{results})
}
func post(w http.ResponseWriter, r *http.Request) {
var post BlogPost
json.NewDecoder(r.Body).Decode(&post)
if verifyPassword(post.Secret) {
messages = append(messages, &post.Content)
writeToDB(post)
w.WriteHeader(http.StatusCreated)
} else {
w.WriteHeader(http.StatusForbidden)
}
}
func hash(pass string) string {
h := sha512.New()
io.WriteString(h, pass)
return hex.EncodeToString(h.Sum(nil))
}
func verifyPassword(pass string) bool {
return hash(pass) == "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429080fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1"
}