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

Commit 7dc554c

Browse files
committed
Move project to go modules
1 parent 1d052ab commit 7dc554c

File tree

5 files changed

+99
-84
lines changed

5 files changed

+99
-84
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/eleksir/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: 82 additions & 0 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,10 +78,12 @@ 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)
6984
return
7085
}
86+
7187
if err := postTemplate.ExecuteTemplate(w, "layout", post); err != nil {
7288
log.Println(err.Error())
7389
errorHandler(w, r, 500)
@@ -97,3 +113,69 @@ func noDirListing(h http.Handler) http.HandlerFunc {
97113
h.ServeHTTP(w, r)
98114
})
99115
}
116+
117+
func readConfig(ConfigName string) (conf *Config, err error) {
118+
var file []byte
119+
120+
file, err = ioutil.ReadFile(ConfigName)
121+
122+
if err != nil {
123+
return nil, err
124+
}
125+
126+
err = yaml.Unmarshal(file, conf)
127+
128+
if err != nil {
129+
return nil, err
130+
}
131+
132+
return conf, nil
133+
}
134+
135+
type post struct {
136+
Title string
137+
Body template.HTML
138+
ModTime int64
139+
}
140+
141+
type postArray struct {
142+
Items map[string]post
143+
sync.RWMutex
144+
}
145+
146+
func newPostArray() *postArray {
147+
p := postArray{}
148+
p.Items = make(map[string]post)
149+
return &p
150+
}
151+
152+
// Get Загружает markdown-файл и конвертирует его в HTML
153+
// Возвращает объект типа Post
154+
// Если путь не существует или является каталогом, то возвращаем ошибку
155+
func (p *postArray) Get(md string) (post, int, error) {
156+
info, err := os.Stat(md)
157+
if err != nil {
158+
if os.IsNotExist(err) {
159+
// файл не существует
160+
return post{}, 404, err
161+
}
162+
return post{}, 500, err
163+
}
164+
if info.IsDir() {
165+
// не файл, а папка
166+
return post{}, 404, fmt.Errorf("dir")
167+
}
168+
val, ok := p.Items[md]
169+
if !ok || (ok && val.ModTime != info.ModTime().UnixNano()) {
170+
p.RLock()
171+
defer p.RUnlock()
172+
fileread, _ := ioutil.ReadFile(md)
173+
lines := strings.Split(string(fileread), "\n")
174+
title := string(lines[0])
175+
body := strings.Join(lines[1:], "\n")
176+
body = string(blackfriday.MarkdownCommon([]byte(body)))
177+
p.Items[md] = post{title, template.HTML(body), info.ModTime().UnixNano()}
178+
}
179+
post := p.Items[md]
180+
return post, 200, nil
181+
}

post.go

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

0 commit comments

Comments
 (0)