comments appearing; need better embedding approach

pull/10/head
Stephen Searles 7 years ago
parent c1fc9ce6d1
commit 432affea76
  1. 54
      comments/comments.go
  2. 2
      http.go

@ -75,7 +75,7 @@ func (cs *Service) ServeComments(post string, w http.ResponseWriter, r *http.Req
if r.Method == "POST" {
return cs.Comment(post, Comment{
Name: user,
Text: r.FormValue("Text"),
Text: readCommentText(r),
IP: r.RemoteAddr,
Date: time.Now(),
})
@ -90,6 +90,12 @@ func (cs *Service) ServeComments(post string, w http.ResponseWriter, r *http.Req
return nil
}
func readCommentText(r *http.Request) string {
comment := struct{ Text string }{}
json.NewDecoder(r.Body).Decode(&comment)
return comment.Text
}
func (cs *Service) Comment(post string, c Comment) error {
return cs.Storage.Store(post, c)
}
@ -101,7 +107,28 @@ func (cs *Service) Load(post string) ([]Comment, error) {
func (cs *Service) WriteHTML(post string, w io.Writer) (int64, error) {
buf := &bytes.Buffer{}
tmpl := template.Must(template.New("").Parse(
`<form onsubmit="javascript:submitComment(event)">
`<style>
comment {
margin: 10px 0;
}
comment, comment name, comment text {
display: block;
}
comment name::after {
content: " says:";
}
comment text {
margin-left: 5px;
padding-left: 5px;
border-left: 2px solid gray;
}
</style>
{{range .}}{{ if .Text }}<comment>
<name>{{.Name}}</name>
<text>{{.Text}}</text>
</comment>
{{end}}{{end}}
<form onsubmit="javascript:submitComment(event)">
<script>
function submitComment(evt) {
var xhr = new XMLHttpRequest();
@ -109,18 +136,24 @@ func (cs *Service) WriteHTML(post string, w io.Writer) (int64, error) {
xhr.send(JSON.stringify({"text": evt.target.querySelector('textarea').value}));
}
</script>
<label>comment<textarea placeholder="comment..."></textarea></label>
<button>post</button>
</form>
{{range $idx, $elem := .}}<comment>
<name>$elem.Name</name>
<text>$elem.Text</name>
</comment>
{{end}}`))
<p>
<div>
<label for="comment">post a comment:</label>
</div>
<div>
<textarea placeholder="comment..." name="comment"></textarea>
</div>
<div>
<button>post</button>
</div>
</p>
</form>`))
comments, err := cs.Load(post)
if err != nil {
return 0, err
}
err = tmpl.Execute(buf, comments)
if err != nil {
return 0, err
@ -260,6 +293,7 @@ func (d *diskvStorage) Retreive(post string) ([]Comment, error) {
if err != nil {
return comments, fmt.Errorf("error unmarshaling comment: %v", err)
}
comments = append(comments, comment)
}
return comments, nil

@ -26,7 +26,7 @@ func (ch *CaddyHugo) ServeHTTPWithNext(next httpserver.Handler, c *caddy.Control
docName := docNameFromCommentRequest(r)
err := ch.Comments.ServeComments(docName, w, r)
if err != nil {
return 500, fmt.Errorf("couldn't load comments")
return 500, fmt.Errorf("couldn't load comments:", err)
}
return 200, nil

Loading…
Cancel
Save