diff --git a/.gitignore b/.gitignore index 66fd13c..ee770a6 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,5 @@ # Dependency directories (remove the comment below to include it) # vendor/ + +.idea/ diff --git a/cmd/blog/main.go b/cmd/blog/main.go new file mode 100644 index 0000000..ab7f2df --- /dev/null +++ b/cmd/blog/main.go @@ -0,0 +1,12 @@ +package main + +import ( + "mxblog/internal/httpserver" + "net/http" +) + +func main() { + h, _ := httpserver.URLRouter() + + http.ListenAndServe(":8080", h) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..c2466a8 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module mxblog + +go 1.13 + +require github.com/go-chi/chi v4.1.1+incompatible diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..c330436 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/go-chi/chi v4.1.1+incompatible h1:MmTgB0R8Bt/jccxp+t6S/1VGIKdJw5J74CK/c9tTfA4= +github.com/go-chi/chi v4.1.1+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ= diff --git a/internal/httpserver/router.go b/internal/httpserver/router.go new file mode 100644 index 0000000..53e7f8e --- /dev/null +++ b/internal/httpserver/router.go @@ -0,0 +1,39 @@ +package httpserver + +import ( + "github.com/go-chi/chi" + "github.com/go-chi/chi/middleware" + "net/http" + "os" + "path/filepath" +) + +func URLRouter() (http.Handler, error) { + templateInit() + r := chi.NewRouter() + + r.Use(middleware.Logger) + + r.NotFound(notFound) + + r.Get("/", func(w http.ResponseWriter, r *http.Request) { + tmp.ExecuteTemplate(w, "home.html", nil) + }) + + staticFileServer(r) + + return r, nil +} + +func staticFileServer(rr chi.Router) { + workDir, _ := os.Getwd() + staticDir := filepath.Join(workDir, "web/static") + + rr.Get("/*", func(w http.ResponseWriter, r *http.Request) { + if fi, err := os.Stat(staticDir + r.RequestURI); os.IsNotExist(err) || fi.IsDir() { + notFound(w, r) + } else { + http.FileServer(http.Dir(staticDir)).ServeHTTP(w, r) + } + }) +} diff --git a/internal/httpserver/view.go b/internal/httpserver/view.go new file mode 100644 index 0000000..6dfb6da --- /dev/null +++ b/internal/httpserver/view.go @@ -0,0 +1,17 @@ +package httpserver + +import ( + "html/template" + "net/http" +) + +var tmp *template.Template + +func templateInit() { + tmp, _ = template.ParseGlob("web/templates/*") +} + +func notFound(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(404) + tmp.ExecuteTemplate(w, "404.html", nil) +} diff --git a/web/static/css/main.css b/web/static/css/main.css new file mode 100644 index 0000000..edbe29b --- /dev/null +++ b/web/static/css/main.css @@ -0,0 +1,3 @@ +body { + background: rgb(50,50,50); +} \ No newline at end of file diff --git a/web/templates/404.html b/web/templates/404.html new file mode 100644 index 0000000..1a054ee --- /dev/null +++ b/web/templates/404.html @@ -0,0 +1,14 @@ + + +
+ +