2023-04-02 18:39:31 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2023-04-02 18:55:48 +00:00
|
|
|
"bytes"
|
2023-04-02 18:39:31 +00:00
|
|
|
"fmt"
|
2023-04-02 18:55:48 +00:00
|
|
|
"html/template"
|
|
|
|
"io/ioutil"
|
2023-04-02 18:39:31 +00:00
|
|
|
"net/http"
|
|
|
|
"path/filepath"
|
|
|
|
|
|
|
|
"github.com/russross/blackfriday/v2"
|
|
|
|
)
|
|
|
|
|
2023-04-02 18:55:48 +00:00
|
|
|
type Page struct {
|
|
|
|
Content template.HTML
|
|
|
|
}
|
|
|
|
|
2023-04-02 18:39:31 +00:00
|
|
|
func renderPage(w http.ResponseWriter, localPath, filePath string) error {
|
|
|
|
content, err := readFileFromRepo(localPath, filePath)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
ext := filepath.Ext(filePath)
|
|
|
|
switch ext {
|
|
|
|
case ".md":
|
|
|
|
renderMarkdown(w, content)
|
|
|
|
case ".html", ".css":
|
|
|
|
renderStatic(w, content, ext)
|
|
|
|
default:
|
|
|
|
return fmt.Errorf("unsupported file format")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func renderMarkdown(w http.ResponseWriter, content []byte) {
|
|
|
|
md := blackfriday.Run(content)
|
2023-04-02 18:55:48 +00:00
|
|
|
|
|
|
|
layout, err := ioutil.ReadFile(filepath.Join(localPath, "assets/_layout.html"))
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, "Layout not found", http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
page := &Page{Content: template.HTML(md)}
|
|
|
|
t, err := template.New("layout").Parse(string(layout))
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, "Error parsing layout", http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var buf bytes.Buffer
|
|
|
|
err = t.Execute(&buf, page)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, "Error rendering layout", http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-04-02 18:39:31 +00:00
|
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
2023-04-02 18:55:48 +00:00
|
|
|
w.Write(buf.Bytes())
|
2023-04-02 18:39:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func renderStatic(w http.ResponseWriter, content []byte, ext string) {
|
|
|
|
contentType := ""
|
|
|
|
switch ext {
|
|
|
|
case ".html":
|
|
|
|
contentType = "text/html; charset=utf-8"
|
|
|
|
case ".css":
|
|
|
|
contentType = "text/css; charset=utf-8"
|
|
|
|
}
|
|
|
|
w.Header().Set("Content-Type", contentType)
|
|
|
|
w.Write(content)
|
|
|
|
}
|