No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

http.go 8.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. package caddyhugo
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "io"
  6. "net"
  7. "net/http"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "git.stephensearles.com/stephen/caddy-hugo2/assets"
  13. "github.com/mholt/caddy"
  14. "github.com/mholt/caddy/caddyhttp/httpserver"
  15. "github.com/spf13/afero"
  16. )
  17. func (ch *CaddyHugo) ServeHTTPWithNext(next httpserver.Handler, w http.ResponseWriter, r *http.Request) (int, error) {
  18. if !ch.Match(r) {
  19. p := path.Join(ch.Dir, "public", r.URL.Path)
  20. http.ServeFile(w, r, p)
  21. return 200, nil
  22. }
  23. if ch.Comments != nil && strings.HasSuffix(r.URL.Path, "/comments") {
  24. docName := docNameFromCommentRequest(r)
  25. err := ch.Comments.ServeComments(docName, w, r)
  26. if err != nil {
  27. return 500, fmt.Errorf("couldn't load comments:", err)
  28. }
  29. return 200, nil
  30. }
  31. if r.URL.Path == "/login" {
  32. return ch.commentsLogin(r, w)
  33. }
  34. if strings.HasPrefix(r.URL.Path, "/hugo/publish") {
  35. err := ch.Publish()
  36. if err != nil {
  37. http.Error(w, err.Error(), http.StatusInternalServerError)
  38. return http.StatusInternalServerError, nil
  39. }
  40. http.Redirect(w, r, "/", http.StatusFound)
  41. return http.StatusFound, nil
  42. }
  43. if strings.HasPrefix(r.URL.Path, "/hugo/simplemde.css") {
  44. w.Write(assets.MustAsset("simplemde/dist/simplemde.min.css"))
  45. return http.StatusOK, nil
  46. }
  47. if strings.HasPrefix(r.URL.Path, "/hugo/simplemde.js") {
  48. w.Write(assets.MustAsset("simplemde/debug/simplemde.js"))
  49. return http.StatusOK, nil
  50. }
  51. if strings.HasPrefix(r.URL.Path, "/hugo/vue.js") {
  52. w.Write(assets.MustAsset("js/vue.js"))
  53. return http.StatusOK, nil
  54. }
  55. if strings.HasPrefix(r.URL.Path, "/hugo/moment.js") {
  56. w.Write(assets.MustAsset("js/moment.js"))
  57. return http.StatusOK, nil
  58. }
  59. if strings.HasPrefix(r.URL.Path, "/hugo/font-awesome.css") {
  60. w.Write(assets.MustAsset("css/font-awesome.min.css"))
  61. return http.StatusOK, nil
  62. }
  63. if strings.HasPrefix(r.URL.Path, "/hugo/admin") {
  64. return ch.Admin().ServeHTTP(w, r)
  65. }
  66. if strings.HasPrefix(r.URL.Path, "/hugo/author") {
  67. return ch.AuthorHome().ServeHTTP(w, r)
  68. }
  69. if strings.HasPrefix(r.URL.Path, "/hugo/edit/") {
  70. return ch.Edit().ServeHTTP(w, r)
  71. }
  72. if strings.HasPrefix(r.URL.Path, "/hugo/draft/") {
  73. return ch.serveDraft(w, r)
  74. }
  75. if strings.HasPrefix(r.URL.Path, "/hugo/media") {
  76. return ch.serveMediaPage(w, r)
  77. }
  78. if strings.HasPrefix(r.URL.Path, "/hugo/upload") {
  79. return ch.uploadMedia(w, r)
  80. }
  81. if strings.HasPrefix(r.URL.Path, "/media/") {
  82. return ch.serveMedia(w, r)
  83. }
  84. if strings.HasPrefix(r.URL.Path, "/hugo/fs/") {
  85. printTree(afero.NewOsFs(), w, ch.Dir)
  86. return 200, nil
  87. }
  88. return next.ServeHTTP(w, r)
  89. }
  90. func (ch *CaddyHugo) ServeNewContent(w http.ResponseWriter, r *http.Request) (int, error) {
  91. name := r.FormValue("name")
  92. ctype := r.FormValue("type")
  93. filename, err := ch.NewContent(name, ctype)
  94. if err != nil {
  95. fmt.Println("error creating new content:", err)
  96. return http.StatusInternalServerError, err
  97. }
  98. // serve redirect
  99. http.Redirect(w, r, filepath.Join("/hugo/edit/", "content", filename), http.StatusFound)
  100. return http.StatusFound, nil
  101. }
  102. func (ch *CaddyHugo) Middleware(c *caddy.Controller) httpserver.Middleware {
  103. return func(next httpserver.Handler) httpserver.Handler {
  104. host := ch.Site.Addr.Host
  105. hostport := net.JoinHostPort(ch.Site.Addr.Host, ch.Site.Addr.Port)
  106. return httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
  107. if r.Host != host && r.Host != hostport {
  108. return next.ServeHTTP(w, r)
  109. }
  110. return ch.ServeHTTPWithNext(next, w, r)
  111. })
  112. }
  113. }
  114. func (ch *CaddyHugo) Auth(r *http.Request) bool {
  115. // this is handled upstream by the caddy configuration
  116. return true
  117. }
  118. func (ch *CaddyHugo) Match(r *http.Request) bool {
  119. host := ch.Site.Addr.Host
  120. hostport := net.JoinHostPort(ch.Site.Addr.Host, ch.Site.Addr.Port)
  121. if r.Host != host && r.Host != hostport {
  122. return false
  123. }
  124. if strings.HasPrefix(r.URL.Path, "/media/") {
  125. return true
  126. }
  127. if strings.HasSuffix(r.URL.Path, "/comments") {
  128. return true
  129. }
  130. if r.URL.Path == "/login" {
  131. return true
  132. }
  133. if r.URL.Path == "/hugo" {
  134. return true
  135. }
  136. return strings.HasPrefix(r.URL.Path, "/hugo/")
  137. }
  138. func (ch *CaddyHugo) Admin() httpserver.Handler {
  139. return httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
  140. err := ch.adminTmpl.Execute(w, ch.TmplData(r, nil))
  141. if err != nil {
  142. fmt.Println(err)
  143. return http.StatusInternalServerError, err
  144. }
  145. return http.StatusOK, nil
  146. })
  147. }
  148. func (ch *CaddyHugo) AuthorHome() httpserver.Handler {
  149. return httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
  150. td := ch.TmplData(r, nil)
  151. err := ch.authorTmpl.Execute(w, td)
  152. if err != nil {
  153. fmt.Println(err)
  154. return http.StatusInternalServerError, err
  155. }
  156. return http.StatusOK, nil
  157. })
  158. }
  159. func (ch *CaddyHugo) Edit() httpserver.Handler {
  160. return httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
  161. if r.URL.Path == "/hugo/edit/new" {
  162. return ch.ServeNewContent(w, r)
  163. }
  164. if r.Header.Get("Upgrade") == "websocket" {
  165. return ch.DeltaWebsocket(w, r)
  166. }
  167. doc, err := ch.editSession(docNameFromEditRequest(r))
  168. if err != nil {
  169. fmt.Println(err)
  170. return http.StatusNotFound, err
  171. }
  172. err = ch.editTmpl.Execute(w, ch.TmplData(r, doc))
  173. if err != nil {
  174. fmt.Println(err)
  175. return http.StatusInternalServerError, err
  176. }
  177. return http.StatusOK, nil
  178. })
  179. }
  180. func (ch *CaddyHugo) serveDraft(w http.ResponseWriter, r *http.Request) (int, error) {
  181. pathSegments := strings.SplitN(r.URL.Path, "/", 5)
  182. if len(pathSegments) < 4 {
  183. return http.StatusNotFound, nil
  184. }
  185. encoded := pathSegments[3]
  186. nameBytes, err := base64.RawURLEncoding.DecodeString(encoded)
  187. if err != nil {
  188. return http.StatusNotFound, err
  189. }
  190. name := string(nameBytes)
  191. ch.mtx.Lock()
  192. defer ch.mtx.Unlock()
  193. docref, ok := ch.docs[ch.docFilename(name)]
  194. if !ok {
  195. return http.StatusNotFound, fmt.Errorf("draft not found")
  196. }
  197. r.URL.Path = strings.ToLower(r.URL.Path)
  198. prefix := "/hugo/draft/" + encoded
  199. r.URL.Path = path.Join("public", r.URL.Path[len(prefix):])
  200. page := ch.HugoSites.GetContentPage(ch.docFilename(name))
  201. if page == nil {
  202. fmt.Fprintf(w, "can't find %q to display a draft", name)
  203. return 404, nil
  204. }
  205. r.URL.Path = page.RelPermalink()
  206. http.FileServer(aferoHTTP{afero.NewBasePathFs(docref.tmpfs, path.Join(ch.Dir, "public"))}).ServeHTTP(w, r)
  207. return 200, nil
  208. }
  209. func printTree(fs afero.Fs, w io.Writer, dir string) {
  210. const (
  211. Line = " │ "
  212. Tab = " "
  213. Elbow = " └─"
  214. Tee = " ├─"
  215. )
  216. wd, _ := os.Getwd()
  217. fmt.Fprintln(w, wd)
  218. if dir == "" {
  219. dir = "/"
  220. }
  221. openDirs := map[string]bool{}
  222. lastFiles := map[string]string{}
  223. afero.Walk(fs, dir, filepath.WalkFunc(func(p string, info os.FileInfo, err error) error {
  224. if strings.HasPrefix(p, "./") {
  225. p = p[2:]
  226. }
  227. openDirs[filepath.Dir(p)] = true
  228. lastFiles[filepath.Dir(p)] = filepath.Base(p)
  229. return nil
  230. }))
  231. afero.Walk(fs, dir, filepath.WalkFunc(func(p string, info os.FileInfo, err error) error {
  232. if err != nil {
  233. return err
  234. }
  235. if strings.HasPrefix(p, "./") {
  236. p = p[2:]
  237. }
  238. if filepath.Base(p)[0] == '.' && info.IsDir() {
  239. return filepath.SkipDir
  240. }
  241. entry := Tee
  242. if lastFiles[filepath.Dir(p)] == filepath.Base(p) {
  243. openDirs[filepath.Dir(p)] = false
  244. entry = Elbow
  245. }
  246. indent := ""
  247. dirs := strings.Split(p, string(filepath.Separator))
  248. dirs = dirs[:len(dirs)-1]
  249. for i := range dirs {
  250. if openDirs[filepath.Join(dirs[:i]...)] {
  251. indent += Line
  252. } else {
  253. indent += Tab
  254. }
  255. }
  256. fmt.Fprintf(w, "%s%s %s (%s)\n", indent, entry, filepath.Base(p), p)
  257. return nil
  258. }))
  259. }
  260. type aferoHTTP struct {
  261. afero.Fs
  262. }
  263. func (a aferoHTTP) Open(name string) (http.File, error) {
  264. af, err := a.Fs.Open(name)
  265. if os.IsExist(err) {
  266. err = os.ErrExist
  267. }
  268. if os.IsNotExist(err) {
  269. err = os.ErrNotExist
  270. }
  271. return af, err
  272. }
  273. func (ch *CaddyHugo) commentsLogin(r *http.Request, w http.ResponseWriter) (int, error) {
  274. if ch.Comments == nil {
  275. return 200, nil
  276. }
  277. _, ok := ch.Comments.User(r)
  278. if !ok {
  279. w.Header().Set("WWW-Authenticate", `Basic realm="Log in with your name and the password. Ask Dan or Stephen for the password."`)
  280. w.WriteHeader(401)
  281. fmt.Fprintf(w, "<html><body>Log in with your name and the password. Ask Dan or Stephen for the password. <a href=%q>go back</a></body></html>", r.Referer())
  282. return 200, nil
  283. }
  284. http.Redirect(w, r, r.Referer(), http.StatusFound)
  285. return 200, nil
  286. }