Browse Source

Переработана структура приложения

master v1.0.0
Krio 4 years ago
parent
commit
db39e60118
  1. 36
      app.go
  2. 37
      main.go

36
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)
}

37
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)
}
}

Loading…
Cancel
Save