2018-11-04 17:52:58 +01:00
package main
import (
"net/http"
"encoding/json"
"log"
"encoding/hex"
"crypto/sha512"
"io"
2018-11-04 19:58:34 +01:00
"html/template"
"os"
2018-11-04 17:52:58 +01:00
)
2018-11-04 19:58:34 +01:00
type OutputFormatter struct {
Author string
Content string
}
type Wrapper struct {
Post OutputFormatter
}
2018-11-04 17:52:58 +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 19:58:34 +01:00
log . Println ( "rip?" )
t := template . New ( "overview" )
//t, err := t.ParseFiles("templates/overview.html")
t , err := t . Parse ( "{{.Author}} said: {{.Content}}" )
if err != nil {
log . Panic ( err )
}
2018-11-04 17:52:58 +01:00
w . WriteHeader ( http . StatusOK )
2018-11-04 19:58:34 +01:00
/ *
2018-11-04 17:52:58 +01:00
w . Write ( [ ] byte ( "response:\n" ) )
for _ , post := range readBlogpostsFromDB ( ) {
w . Write ( [ ] byte ( post . Content ) )
}
2018-11-04 19:58:34 +01:00
* /
//results := readBlogpostsFromDB()
//t.Execute(w, OutputFormatter{Author: results[0].Author, Content: results[0].Content})
t . Execute ( w , "asdasd" )
t . Execute ( os . Stdout , "asdasd" )
//err = t.Execute(os.Stdout, OutputFormatter{Author: results[0].Author, Content: results[0].Content})
log . Println ( err )
2018-11-04 17:52:58 +01:00
}
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"
}