Tuesday 27 October 2020

go web app 10 post

page loaded

post request, server save comment in memory, then page get updated comments from server


//tutorial.go
package main

import (
"html/template"
"net/http"

"github.com/gorilla/mux"
)

var templates *template.Template
var comments = []string{"line1", "line2", "line3"}

func indexGetHandler(w http.ResponseWriter, r *http.Request) {
templates.ExecuteTemplate(w, "index.html", comments)
}

func indexPostHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
comment := r.PostForm.Get("textarea1")
comments = append(comments, comment)
templates.ExecuteTemplate(w, "index.html", comments)
}

func main() {
templates = template.Must(template.ParseGlob("templates/*.html"))
r := mux.NewRouter()
r.HandleFunc("/", indexGetHandler).Methods("GET")
r.HandleFunc("/", indexPostHandler).Methods("POST")
http.Handle("/", r)
http.ListenAndServe(":8000", nil)
}

---------------------------
//index.html
<html>

<head>
    <title> Comments</title>
</head>

<body>
    <h1>Comments</h1>
    <form method="POST">
        <textarea name="textarea1"></textarea>
        <div>
            <button type="submit">Post Comment</button>
        </div>
    </form>
    {{range .}}
    <div>{{.}}</div>
    {{end}}
</body>

</html>

reference:

No comments:

Post a Comment