This repository has been archived by the owner on Jul 16, 2019. It is now read-only.
/
main.go
61 lines (48 loc) · 1.49 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
package main // import "github.com/Luzifer/ipfs-markdown"
import (
"fmt"
"io"
"net/http"
"github.com/Luzifer/rconfig"
"github.com/flosch/pongo2"
"github.com/gorilla/mux"
)
//go:generate go-bindata -o bindata.go viewer.html
type config struct {
IPFSGateway string `flag:"gateway" default:"https://ipfs.io" description:"Gateway to fetch markdown from"`
Branding string `flag:"branding" default:"IPFS-Markdown-Viewer" description:"Branding to show on page"`
Listen string `flag:"listen" default:":3000" description:"IP/Port to listen on"`
}
var (
cfg = &config{}
version = "dev"
)
func main() {
rconfig.Parse(cfg)
r := mux.NewRouter()
r.HandleFunc("/document/{ipfs_hash:Qm.+}", handleDocument)
r.HandleFunc("/{ipfs_hash:Qm.+}", handleViewer)
http.Handle("/", r)
http.ListenAndServe(cfg.Listen, r)
}
func handleViewer(res http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
tplData, _ := Asset("viewer.html")
tpl := pongo2.Must(pongo2.FromString(string(tplData)))
tpl.ExecuteWriter(pongo2.Context{
"ipfs_hash": vars["ipfs_hash"],
"branding": cfg.Branding,
}, res)
}
func handleDocument(res http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
documentURL := fmt.Sprintf("%s/ipfs/%s", cfg.IPFSGateway, vars["ipfs_hash"])
resp, err := http.Get(documentURL)
if err != nil {
http.Error(res, "An error ocurred", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
res.Header().Set("Content-Type", "text/markdown")
io.Copy(res, resp.Body)
}