update.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package main
  2. import (
  3. "flag"
  4. "io/ioutil"
  5. "net/http"
  6. "path"
  7. "zero/core/conf"
  8. "zero/core/hash"
  9. "zero/core/lang"
  10. "zero/core/logx"
  11. "zero/tools/goctl/update/config"
  12. "zero/tools/goctl/util"
  13. )
  14. const (
  15. contentMd5Header = "Content-Md5"
  16. filename = "goctl"
  17. )
  18. var configFile = flag.String("f", "etc/update-api.json", "the config file")
  19. func forChksumHandler(file string, next http.Handler) http.Handler {
  20. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  21. if !util.FileExists(file) {
  22. logx.Errorf("file %q not exist", file)
  23. http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
  24. return
  25. }
  26. content, err := ioutil.ReadFile(file)
  27. if err != nil {
  28. logx.Error(err)
  29. http.Error(w, err.Error(), http.StatusInternalServerError)
  30. return
  31. }
  32. chksum := hash.Md5Hex(content)
  33. if chksum == r.Header.Get(contentMd5Header) {
  34. w.WriteHeader(http.StatusNotModified)
  35. return
  36. } else {
  37. w.Header().Set(contentMd5Header, chksum)
  38. }
  39. next.ServeHTTP(w, r)
  40. })
  41. }
  42. func main() {
  43. flag.Parse()
  44. var c config.Config
  45. conf.MustLoad(*configFile, &c)
  46. fs := http.FileServer(http.Dir(c.FileDir))
  47. http.Handle(c.FilePath, http.StripPrefix(c.FilePath, forChksumHandler(path.Join(c.FileDir, filename), fs)))
  48. lang.Must(http.ListenAndServe(c.ListenOn, nil))
  49. }