update.go 1.4 KB

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