From db39e60118e648bf6518f35cbebdf9dcdd900560 Mon Sep 17 00:00:00 2001 From: Krio Date: Fri, 20 Aug 2021 09:09:47 +0700 Subject: [PATCH] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=B0=D0=BD=D0=B0=20=D1=81=D1=82=D1=80=D1=83=D0=BA?= =?UTF-8?q?=D1=82=D1=83=D1=80=D0=B0=20=D0=BF=D1=80=D0=B8=D0=BB=D0=BE=D0=B6?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app.go | 36 ++++++++++++++++++++++++++++++++++++ main.go | 37 +++++-------------------------------- 2 files changed, 41 insertions(+), 32 deletions(-) create mode 100644 app.go diff --git a/app.go b/app.go new file mode 100644 index 0000000..3a4d095 --- /dev/null +++ b/app.go @@ -0,0 +1,36 @@ +package main + +import ( + "html/template" + "log" + "net/http" +) + +type App struct { + store TxtStore +} + +func (a *App) mainPageHandler(writer http.ResponseWriter, request *http.Request) { + html, err := template.ParseFS(staticFiles, "static/index.html") + if err != nil { + log.Fatal(err) + } + + guestbook, err := a.store.GetGuestbook() + if err != nil { + log.Fatal(err) + } + + if err := html.Execute(writer, guestbook); err != nil { + log.Fatal(err) + } +} + +func (a *App) newCommentHandler(writer http.ResponseWriter, request *http.Request) { + comment := request.FormValue("comment") + if err := a.store.AddComment(comment); err != nil { + log.Fatal(err) + } + + http.Redirect(writer, request, "/", http.StatusFound) +} diff --git a/main.go b/main.go index 8818851..ad5092a 100644 --- a/main.go +++ b/main.go @@ -2,7 +2,6 @@ package main import ( "embed" - "html/template" "log" "net/http" ) @@ -15,41 +14,15 @@ type Guestbook struct { Count int } -func indexHandler(writer http.ResponseWriter, request *http.Request) { - html, err := template.ParseFS(staticFiles, "static/index.html") - check(err) - - store := TxtStore("comments.txt") - guestbook, err := store.GetGuestbook() - check(err) - - err = html.Execute(writer, guestbook) - check(err) -} - -func newHandler(writer http.ResponseWriter, request *http.Request) { - comment := request.FormValue("comment") - store := TxtStore("comments.txt") - - err := store.AddComment(comment) - check(err) - - http.Redirect(writer, request, "/", http.StatusFound) -} - func main() { - http.HandleFunc("/", indexHandler) - http.HandleFunc("/new", newHandler) + app := App{store: TxtStore("comments.txt")} + + http.HandleFunc("/", app.mainPageHandler) + http.HandleFunc("/new", app.newCommentHandler) var staticFS = http.FS(staticFiles) http.Handle("/static/", http.FileServer(staticFS)) - err := http.ListenAndServe("0.0.0.0:80", nil) + err := http.ListenAndServe(":80", nil) log.Fatal(err) } - -func check(err error) { - if err != nil { - log.Fatal(err) - } -}