This repository was archived by the owner on Sep 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
198 lines (154 loc) · 4.87 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package main
import (
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"strings"
"sync"
"github.com/bmizerany/pat"
"github.com/russross/blackfriday"
"gopkg.in/yaml.v2"
)
const (
configFileName = "mdserver.yaml"
)
// Config - структура для считывания конфигурационного файла
type Config struct {
Listen string `yaml:"listen"`
}
var (
// компилируем шаблоны, если не удалось, то выходим
postTemplate = template.Must(template.ParseFiles(path.Join("templates", "layout.html"), path.Join("templates", "post.html")))
errorTemplate = template.Must(template.ParseFiles(path.Join("templates", "layout.html"), path.Join("templates", "error.html")))
posts = newPostArray()
)
func main() {
cfg, err := readConfig(configFileName)
if err != nil {
log.Fatalln(err)
}
// для отдачи сервером статичных файлов из папки public/static
fs := noDirListing(http.FileServer(http.Dir("./public/static")))
http.Handle("/static/", http.StripPrefix("/static/", fs))
uploads := noDirListing(http.FileServer(http.Dir("./public/uploads")))
http.Handle("/uploads/", http.StripPrefix("/uploads/", uploads))
mux := pat.New()
mux.Get("/:page", http.HandlerFunc(postHandler))
mux.Get("/:page/", http.HandlerFunc(postHandler))
mux.Get("/", http.HandlerFunc(postHandler))
http.Handle("/", mux)
log.Printf("Listening %s...", cfg.Listen)
log.Fatalln(http.ListenAndServe(cfg.Listen, nil))
}
func postHandler(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
// Извлекаем параметр
// Например, в http://127.0.0.1:3000/p1 page = "p1"
// в http://127.0.0.1:3000/ page = ""
page := params.Get(":page")
// Путь к файлу (без расширения)
// Например, posts/p1
p := path.Join("posts", page)
var postMD string
if page != "" {
// если page не пусто, то считаем, что запрашивается файл
// получим posts/p1.md
postMD = p + ".md"
} else {
// если page пусто, то выдаем главную
postMD = p + "/index.md"
}
post, status, err := posts.Get(postMD)
if err != nil {
errorHandler(w, r, status)
return
}
err := postTemplate.ExecuteTemplate(w, "layout", post)
if err != nil {
log.Println(err.Error())
errorHandler(w, r, 500)
}
}
func errorHandler(w http.ResponseWriter, r *http.Request, status int) {
log.Printf("error %d %s %s\n", status, r.RemoteAddr, r.URL.Path)
w.WriteHeader(status)
err := errorTemplate.ExecuteTemplate(w, "layout", map[string]interface{}{"Error": http.StatusText(status), "Status": status})
if err != nil {
log.Println(err.Error())
http.Error(w, http.StatusText(500), 500)
return
}
}
// обертка для http.FileServer, чтобы она не выдавала список файлов
// например, если открыть http://127.0.0.1:3000/static/,
// то будет видно список файлов внутри каталога.
// noDirListing - вернет 404 ошибку в этом случае.
func noDirListing(h http.Handler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/") || r.URL.Path == "" {
http.NotFound(w, r)
return
}
h.ServeHTTP(w, r)
})
}
func readConfig(ConfigName string) (conf *Config, err error) {
var file []byte
file, err = ioutil.ReadFile(ConfigName)
if err != nil {
return nil, err
}
err = yaml.Unmarshal(file, conf)
if err != nil {
return nil, err
}
return conf, nil
}
type post struct {
Title string
Body template.HTML
ModTime int64
}
type postArray struct {
Items map[string]post
sync.RWMutex
}
func newPostArray() *postArray {
p := postArray{}
p.Items = make(map[string]post)
return &p
}
// Get Загружает markdown-файл и конвертирует его в HTML
// Возвращает объект типа Post
// Если путь не существует или является каталогом, то возвращаем ошибку
func (p *postArray) Get(md string) (post, int, error) {
info, err := os.Stat(md)
if err != nil {
if os.IsNotExist(err) {
// файл не существует
return post{}, 404, err
}
return post{}, 500, err
}
if info.IsDir() {
// не файл, а папка
return post{}, 404, fmt.Errorf("dir")
}
val, ok := p.Items[md]
if !ok || (ok && val.ModTime != info.ModTime().UnixNano()) {
p.RLock()
defer p.RUnlock()
fileread, _ := ioutil.ReadFile(md)
lines := strings.Split(string(fileread), "\n")
title := string(lines[0])
body := strings.Join(lines[1:], "\n")
body = string(blackfriday.MarkdownCommon([]byte(body)))
p.Items[md] = post{title, template.HTML(body), info.ModTime().UnixNano()}
}
post := p.Items[md]
return post, 200, nil
}