Skip to content
This repository was archived by the owner on Sep 22, 2022. It is now read-only.

Commit 388ff6a

Browse files
authored
Merge pull request #2 from eleksir/gomodules
Gomodules
2 parents 1d052ab + 4f75c71 commit 388ff6a

File tree

7 files changed

+120
-88
lines changed

7 files changed

+120
-88
lines changed

config.go

Lines changed: 0 additions & 24 deletions
This file was deleted.

go.mod

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
module github.com/zaz600/mdserver
2+
3+
go 1.16
4+
5+
require (
6+
github.com/bmizerany/pat v0.0.0-20210406213842-e4b6760bdd6f
7+
github.com/russross/blackfriday v1.6.0
8+
gopkg.in/yaml.v2 v2.4.0
9+
)

go.sum

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
github.com/bmizerany/pat v0.0.0-20210406213842-e4b6760bdd6f h1:gOO/tNZMjjvTKZWpY7YnXC72ULNLErRtp94LountVE8=
2+
github.com/bmizerany/pat v0.0.0-20210406213842-e4b6760bdd6f/go.mod h1:8rLXio+WjiTceGBHIoTvn60HIbs7Hm7bcHjyrSqYB9c=
3+
github.com/russross/blackfriday v1.6.0 h1:KqfZb0pUVN2lYqZUYRddxF4OR8ZMURnJIG5Y3VRLtww=
4+
github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY=
5+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
6+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
7+
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
8+
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=

mdserver.go renamed to main.go

Lines changed: 101 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,30 @@
11
package main
22

33
import (
4+
"fmt"
45
"html/template"
6+
"io/ioutil"
57
"log"
68
"net/http"
9+
"os"
710
"path"
811
"strings"
12+
"sync"
913

1014
"github.com/bmizerany/pat"
15+
"github.com/russross/blackfriday"
16+
"gopkg.in/yaml.v2"
1117
)
1218

1319
const (
1420
configFileName = "mdserver.yaml"
1521
)
1622

23+
// Config - структура для считывания конфигурационного файла
24+
type Config struct {
25+
Listen string `yaml:"listen"`
26+
}
27+
1728
var (
1829
// компилируем шаблоны, если не удалось, то выходим
1930
postTemplate = template.Must(template.ParseFiles(path.Join("templates", "layout.html"), path.Join("templates", "post.html")))
@@ -23,9 +34,11 @@ var (
2334

2435
func main() {
2536
cfg, err := readConfig(configFileName)
37+
2638
if err != nil {
2739
log.Fatalln(err)
2840
}
41+
2942
// для отдачи сервером статичных файлов из папки public/static
3043
fs := noDirListing(http.FileServer(http.Dir("./public/static")))
3144
http.Handle("/static/", http.StripPrefix("/static/", fs))
@@ -54,6 +67,7 @@ func postHandler(w http.ResponseWriter, r *http.Request) {
5467
p := path.Join("posts", page)
5568

5669
var postMD string
70+
5771
if page != "" {
5872
// если page не пусто, то считаем, что запрашивается файл
5973
// получим posts/p1.md
@@ -64,11 +78,16 @@ func postHandler(w http.ResponseWriter, r *http.Request) {
6478
}
6579

6680
post, status, err := posts.Get(postMD)
81+
6782
if err != nil {
6883
errorHandler(w, r, status)
84+
6985
return
7086
}
71-
if err := postTemplate.ExecuteTemplate(w, "layout", post); err != nil {
87+
88+
err := postTemplate.ExecuteTemplate(w, "layout", post)
89+
90+
if err != nil {
7291
log.Println(err.Error())
7392
errorHandler(w, r, 500)
7493
}
@@ -77,9 +96,13 @@ func postHandler(w http.ResponseWriter, r *http.Request) {
7796
func errorHandler(w http.ResponseWriter, r *http.Request, status int) {
7897
log.Printf("error %d %s %s\n", status, r.RemoteAddr, r.URL.Path)
7998
w.WriteHeader(status)
80-
if err := errorTemplate.ExecuteTemplate(w, "layout", map[string]interface{}{"Error": http.StatusText(status), "Status": status}); err != nil {
99+
100+
err := errorTemplate.ExecuteTemplate(w, "layout", map[string]interface{}{"Error": http.StatusText(status), "Status": status})
101+
102+
if err != nil {
81103
log.Println(err.Error())
82104
http.Error(w, http.StatusText(500), 500)
105+
83106
return
84107
}
85108
}
@@ -92,8 +115,84 @@ func noDirListing(h http.Handler) http.HandlerFunc {
92115
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
93116
if strings.HasSuffix(r.URL.Path, "/") || r.URL.Path == "" {
94117
http.NotFound(w, r)
118+
95119
return
96120
}
121+
97122
h.ServeHTTP(w, r)
98123
})
99124
}
125+
126+
func readConfig(ConfigName string) (conf *Config, err error) {
127+
var file []byte
128+
129+
file, err = ioutil.ReadFile(ConfigName)
130+
131+
if err != nil {
132+
return nil, err
133+
}
134+
135+
err = yaml.Unmarshal(file, conf)
136+
137+
if err != nil {
138+
return nil, err
139+
}
140+
141+
return conf, nil
142+
}
143+
144+
type post struct {
145+
Title string
146+
Body template.HTML
147+
ModTime int64
148+
}
149+
150+
type postArray struct {
151+
Items map[string]post
152+
sync.RWMutex
153+
}
154+
155+
func newPostArray() *postArray {
156+
p := postArray{}
157+
p.Items = make(map[string]post)
158+
159+
return &p
160+
}
161+
162+
// Get Загружает markdown-файл и конвертирует его в HTML
163+
// Возвращает объект типа Post
164+
// Если путь не существует или является каталогом, то возвращаем ошибку
165+
func (p *postArray) Get(md string) (post, int, error) {
166+
info, err := os.Stat(md)
167+
168+
if err != nil {
169+
if os.IsNotExist(err) {
170+
// файл не существует
171+
return post{}, 404, err
172+
}
173+
174+
return post{}, 500, err
175+
}
176+
177+
if info.IsDir() {
178+
// не файл, а папка
179+
return post{}, 404, fmt.Errorf("dir")
180+
}
181+
182+
val, ok := p.Items[md]
183+
184+
if !ok || (ok && val.ModTime != info.ModTime().UnixNano()) {
185+
p.RLock()
186+
defer p.RUnlock()
187+
fileread, _ := ioutil.ReadFile(md)
188+
lines := strings.Split(string(fileread), "\n")
189+
title := string(lines[0])
190+
body := strings.Join(lines[1:], "\n")
191+
body = string(blackfriday.MarkdownCommon([]byte(body)))
192+
p.Items[md] = post{title, template.HTML(body), info.ModTime().UnixNano()}
193+
}
194+
195+
post := p.Items[md]
196+
197+
return post, 200, nil
198+
}

mdserver.yaml.example

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
listen: 0.0.0.0:8890
1+
listen: 0.0.0.0:8890

post.go

Lines changed: 0 additions & 60 deletions
This file was deleted.

public/static/stylesheets/main.css

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
body { padding-bottom: 70px; padding-top: 70px; }
1+
body { padding-bottom: 70px; padding-top: 70px; }
22
#container
33
{
44
background:#fff;

0 commit comments

Comments
 (0)