package main
import (
"fmt"
"log"
"net/http"
"strconv"
)
func genpost(rw http.ResponseWriter, req *http.Request) {
var pid int
_, err := fmt.Sscanf(req.URL.Query().Get("id"), "%x", &pid)
if err != nil {
http.Error(rw, err.Error(), http.StatusNotAcceptable)
return
}
if req.Method == http.MethodPost {
err := req.ParseForm()
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
name, pass, ok := req.BasicAuth()
if !ok || !checkPasswd(name, pass) {
rw.Header().Set("WWW-Authenticate", "Basic realm=\"Credentials\"")
http.Error(rw, "Invalid password", http.StatusUnauthorized)
return
}
if req.FormValue("response") == "" {
http.Error(rw, "No response", http.StatusBadRequest)
return
}
cid, err := strconv.Atoi(req.FormValue("rtid"))
if err != nil {
cid = -1
}
nid, err := Comment{ // nid: new (comment) id
Name: name,
Text: req.FormValue("response"),
}.addComment(pid, cid)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(rw, req, fmt.Sprintf("./post?id=%x#%d", pid, nid), http.StatusFound)
} else {
link, err := queryLink(pid)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
if err := tmpl.ExecuteTemplate(rw, "post.gtml", link); err != nil {
log.Fatal(err)
}
}
}