blob: 9510a3d36bd1b0766c9e8914b9b3ce64280642c2 [file] [log] [blame]
Serge Bazanskia7674672021-05-30 21:09:34 +00001package main
2
3import (
4 "flag"
5 "fmt"
6 "mime"
7 "net/http"
8 "strings"
Serge Bazanski3c9092a2021-05-30 23:15:20 +00009 "sync"
Serge Bazanskia7674672021-05-30 21:09:34 +000010
11 "code.hackerspace.pl/hscloud/go/mirko"
12 "github.com/golang/glog"
13
14 "code.hackerspace.pl/hscloud/hswaw/site/static"
15)
16
17var (
18 flagSitePublic string
19)
20
21type service struct {
Serge Bazanski3c9092a2021-05-30 23:15:20 +000022 // feeds is a map from atom feed name to atom feed. This is updated by a
23 // background worker.
24 feeds map[string]*atomFeed
25 // feedsMu locks the feeds field.
26 feedsMu sync.RWMutex
Serge Bazanskia7674672021-05-30 21:09:34 +000027}
28
29func main() {
30 flag.StringVar(&flagSitePublic, "site_public", "0.0.0.0:8080", "Address at which to serve public HTTP requests")
31 flag.Parse()
32
33 mi := mirko.New()
34 if err := mi.Listen(); err != nil {
35 glog.Exitf("Listen failed: %v", err)
36 }
37
38 s := &service{}
Serge Bazanski3c9092a2021-05-30 23:15:20 +000039 go s.feedWorker(mi.Context())
Serge Bazanskia7674672021-05-30 21:09:34 +000040
41 mux := http.NewServeMux()
42 s.registerHTTP(mux)
43
44 go func() {
45 glog.Infof("Listening for public HTTP at %v", flagSitePublic)
46 if err := http.ListenAndServe(flagSitePublic, mux); err != nil {
47 glog.Exit(err)
48 }
49 }()
50
51 if err := mi.Serve(); err != nil {
52 glog.Exitf("Serve failed: %v", err)
53 }
54
55 <-mi.Done()
56}
57
58func (s *service) handleHTTPStatic(w http.ResponseWriter, r *http.Request) {
59 path := strings.TrimPrefix(r.URL.Path, "/")
60
61 staticPath := fmt.Sprintf("hswaw/site/%s", path)
Serge Bazanskia7674672021-05-30 21:09:34 +000062 if data, ok := static.Data[staticPath]; ok {
63 parts := strings.Split(path, ".")
64 ext := fmt.Sprintf(".%s", parts[len(parts)-1])
65 t := mime.TypeByExtension(ext)
66 w.Header().Set("Content-Type", t)
67 w.Write(data)
68 } else {
69 http.NotFound(w, r)
70 }
71}
72
73func (s *service) registerHTTP(mux *http.ServeMux) {
74 mux.HandleFunc("/static/", s.handleHTTPStatic)
Serge Bazanski4d7b2f02021-05-31 22:33:51 +000075 mux.HandleFunc("/", s.handleIndex)
Serge Bazanskia7674672021-05-30 21:09:34 +000076}