1
0
mirror of https://github.com/danog/gojekyll.git synced 2024-11-27 12:44:54 +01:00
gojekyll/server.go

70 lines
1.4 KiB
Go
Raw Normal View History

package main
import (
"fmt"
2017-06-17 02:49:44 +02:00
"log"
"net/http"
2017-06-17 02:49:44 +02:00
"github.com/fsnotify/fsnotify"
)
// Server serves the site on HTTP.
2017-06-17 02:49:44 +02:00
type Server struct{ Site *Site }
// Run runs the server.
func (s *Server) Run() error {
address := "localhost:4000"
if err := s.watchFiles(); err != nil {
2017-06-17 02:49:44 +02:00
return err
}
printSetting("Server address:", "http://"+address+"/")
printSetting("Server running...", "press ctrl-c to stop.")
http.HandleFunc("/", s.handler)
2017-06-12 02:05:17 +02:00
return http.ListenAndServe(address, nil)
}
2017-06-17 02:49:44 +02:00
func (s *Server) handler(w http.ResponseWriter, r *http.Request) {
2017-06-17 04:09:25 +02:00
site := s.Site
2017-06-17 02:06:55 +02:00
urlpath := r.URL.Path
// TODO? w.Header().Set("Content-Type", "text/plain; charset=utf-8")
p, found := site.PageForURL(urlpath)
if !found {
w.WriteHeader(http.StatusNotFound)
p, found = site.Paths["404.html"]
}
if !found {
2017-06-17 02:06:55 +02:00
fmt.Fprintf(w, "404 page not found: %s", urlpath)
return
}
err := p.Write(w)
if err != nil {
2017-06-17 02:06:55 +02:00
fmt.Printf("Error rendering %s: %s", urlpath, err)
2017-06-12 02:05:17 +02:00
}
}
2017-06-17 02:49:44 +02:00
func (s *Server) watchFiles() error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
go func() {
for {
select {
case event := <-watcher.Events:
log.Println("event:", event)
if event.Op&fsnotify.Write == fsnotify.Write {
log.Println("modified file:", event.Name)
// TODO rebuild the site
}
case err := <-watcher.Errors:
log.Println("error:", err)
}
}
}()
return watcher.Add(s.Site.Source)
}