Serge Bazanski | a767467 | 2021-05-30 21:09:34 +0000 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "flag" |
| 5 | "fmt" |
| 6 | "mime" |
| 7 | "net/http" |
| 8 | "strings" |
| 9 | |
| 10 | "code.hackerspace.pl/hscloud/go/mirko" |
| 11 | "github.com/golang/glog" |
| 12 | |
| 13 | "code.hackerspace.pl/hscloud/hswaw/site/static" |
| 14 | ) |
| 15 | |
| 16 | var ( |
| 17 | flagSitePublic string |
| 18 | ) |
| 19 | |
| 20 | type service struct { |
| 21 | } |
| 22 | |
| 23 | func main() { |
| 24 | flag.StringVar(&flagSitePublic, "site_public", "0.0.0.0:8080", "Address at which to serve public HTTP requests") |
| 25 | flag.Parse() |
| 26 | |
| 27 | mi := mirko.New() |
| 28 | if err := mi.Listen(); err != nil { |
| 29 | glog.Exitf("Listen failed: %v", err) |
| 30 | } |
| 31 | |
| 32 | s := &service{} |
| 33 | |
| 34 | mux := http.NewServeMux() |
| 35 | s.registerHTTP(mux) |
| 36 | |
| 37 | go func() { |
| 38 | glog.Infof("Listening for public HTTP at %v", flagSitePublic) |
| 39 | if err := http.ListenAndServe(flagSitePublic, mux); err != nil { |
| 40 | glog.Exit(err) |
| 41 | } |
| 42 | }() |
| 43 | |
| 44 | if err := mi.Serve(); err != nil { |
| 45 | glog.Exitf("Serve failed: %v", err) |
| 46 | } |
| 47 | |
| 48 | <-mi.Done() |
| 49 | } |
| 50 | |
| 51 | func (s *service) handleHTTPStatic(w http.ResponseWriter, r *http.Request) { |
| 52 | path := strings.TrimPrefix(r.URL.Path, "/") |
| 53 | |
| 54 | staticPath := fmt.Sprintf("hswaw/site/%s", path) |
| 55 | glog.Infof("%q", staticPath) |
| 56 | if data, ok := static.Data[staticPath]; ok { |
| 57 | parts := strings.Split(path, ".") |
| 58 | ext := fmt.Sprintf(".%s", parts[len(parts)-1]) |
| 59 | t := mime.TypeByExtension(ext) |
| 60 | w.Header().Set("Content-Type", t) |
| 61 | w.Write(data) |
| 62 | } else { |
| 63 | http.NotFound(w, r) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | func (s *service) registerHTTP(mux *http.ServeMux) { |
| 68 | mux.HandleFunc("/static/", s.handleHTTPStatic) |
| 69 | } |