$ go mod init webapp
$ mkdir -p cmd/web
$ mkdir -p internal/handlers
$ mkdir html
$ touch cmd/web/main.go
$ touch cmd/web/routes.go
$ touch html/home.jet
$ touch internal/handlers/handlers.go
home.jetは、Webページのテンプレートファイル
home.jet
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>jet test</h1> </body> </html>
handlers.go
package handlers import ( "log" "net/http" "github.com/CloudyKit/jet/v6" ) var views = jet.NewSet( jet.NewOSFileSystemLoader("./html"), jet.InDevelopmentMode(), ) func Home(w http.ResponseWriter, r *http.Request){ err := renderPage(w, "home.jet", nil) if err != nil { log.Println(err) } } func renderPage(w http.ResponseWriter, tmpl string, data jet.VarMap) error { view, err := views.GetTemplate(tmpl) if err != nil { log.Println(err) return err } err = view.Execute(w, data, nil) if err != nil { log.Println(err) return err } return nil }
route.go
package main import ( "webapp/internal/handlers" "net/http" "github.com/bmizerany/pat" ) func routes() http.Handler { mux := pat.New() mux.Get("/", http.HandlerFunc(handlers.Home)) return mux }
main.go
package main import ( "log" "net/http" ) func main(){ mux := routes() log.Println("Starting web server on port 8080") _ = http.ListenAndServe(":8080", mux) }
$ go run cmd/web/*.go
Echoとかを使わずに、jetなど色々な書き方があるんやな
Webサーバーの作成には、bmizerany/patモジュールを使用