Split into separate files, add authentication
parent
a2e3f7c845
commit
f7b775cb38
@ -0,0 +1,46 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"encoding/hex"
|
||||
"crypto/sha512"
|
||||
"io"
|
||||
)
|
||||
|
||||
func startServer() {
|
||||
http.HandleFunc("/", get)
|
||||
http.HandleFunc("/add", post)
|
||||
log.Fatal(http.ListenAndServe(":12345", nil))
|
||||
}
|
||||
|
||||
func get(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("response:\n"))
|
||||
for _, post := range readBlogpostsFromDB() {
|
||||
w.Write([]byte(post.Content))
|
||||
}
|
||||
}
|
||||
|
||||
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"
|
||||
}
|
Loading…
Reference in new issue