llist/genpost.go -rw-r--r-- 1.4 KiB View raw
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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)
		}
	}
}