https_server.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. package http_server
  2. import (
  3. "bytes"
  4. "embed"
  5. "encoding/hex"
  6. "encoding/json"
  7. "fmt"
  8. log "github.com/sirupsen/logrus"
  9. "github.com/spf13/cast"
  10. "io/fs"
  11. olog "log"
  12. "math/rand"
  13. "net"
  14. "net/http"
  15. "os"
  16. "pmail/config"
  17. "pmail/controllers"
  18. "pmail/controllers/email"
  19. "pmail/dto"
  20. "pmail/dto/response"
  21. "pmail/i18n"
  22. "pmail/session"
  23. "time"
  24. )
  25. //go:embed dist/*
  26. var local embed.FS
  27. const HttpsPort = 443
  28. var httpsServer *http.Server
  29. type nullWrite struct {
  30. }
  31. func (w *nullWrite) Write(p []byte) (int, error) {
  32. return len(p), nil
  33. }
  34. func HttpsStart() {
  35. log.Infof("Http Server Start")
  36. mux := http.NewServeMux()
  37. fe, err := fs.Sub(local, "dist")
  38. if err != nil {
  39. panic(err)
  40. }
  41. mux.Handle("/", http.FileServer(http.FS(fe)))
  42. mux.HandleFunc("/api/ping", contextIterceptor(controllers.Ping))
  43. mux.HandleFunc("/api/login", contextIterceptor(controllers.Login))
  44. mux.HandleFunc("/api/group", contextIterceptor(controllers.GetUserGroup))
  45. mux.HandleFunc("/api/email/list", contextIterceptor(email.EmailList))
  46. mux.HandleFunc("/api/email/detail", contextIterceptor(email.EmailDetail))
  47. mux.HandleFunc("/api/email/send", contextIterceptor(email.Send))
  48. mux.HandleFunc("/api/settings/modify_password", contextIterceptor(controllers.ModifyPassword))
  49. mux.HandleFunc("/attachments/", contextIterceptor(controllers.GetAttachments))
  50. mux.HandleFunc("/attachments/download/", contextIterceptor(controllers.Download))
  51. // go http server会打一堆没用的日志,写一个空的日志处理器,屏蔽掉日志输出
  52. nullLog := olog.New(&nullWrite{}, "", olog.Ldate)
  53. httpsServer = &http.Server{
  54. Addr: fmt.Sprintf(":%d", HttpsPort),
  55. Handler: session.Instance.LoadAndSave(mux),
  56. ReadTimeout: time.Second * 60,
  57. WriteTimeout: time.Second * 60,
  58. ErrorLog: nullLog,
  59. }
  60. err = httpsServer.ListenAndServeTLS("config/ssl/public.crt", "config/ssl/private.key")
  61. if err != nil {
  62. panic(err)
  63. }
  64. }
  65. func HttpsStop() {
  66. if httpsServer != nil {
  67. httpsServer.Close()
  68. }
  69. }
  70. func genLogID() string {
  71. r := rand.New(rand.NewSource(time.Now().UnixMicro()))
  72. if ip == "" {
  73. ip = getLocalIP()
  74. }
  75. now := time.Now()
  76. timestamp := uint32(now.Unix())
  77. timeNano := now.UnixNano()
  78. pid := os.Getpid()
  79. b := bytes.Buffer{}
  80. b.WriteString(hex.EncodeToString(net.ParseIP(ip).To4()))
  81. b.WriteString(fmt.Sprintf("%x", timestamp&0xffffffff))
  82. b.WriteString(fmt.Sprintf("%04x", timeNano&0xffff))
  83. b.WriteString(fmt.Sprintf("%04x", pid&0xffff))
  84. b.WriteString(fmt.Sprintf("%06x", r.Int31n(1<<24)))
  85. b.WriteString("b0")
  86. return b.String()
  87. }
  88. // 注入context
  89. func contextIterceptor(h controllers.HandlerFunc) http.HandlerFunc {
  90. return func(w http.ResponseWriter, r *http.Request) {
  91. if w.Header().Get("Content-Type") == "" {
  92. w.Header().Set("Content-Type", "application/json")
  93. }
  94. ctx := &dto.Context{}
  95. ctx.Context = r.Context()
  96. ctx.SetValue(dto.LogID, genLogID())
  97. lang := r.Header.Get("Lang")
  98. if lang == "" {
  99. lang = "en"
  100. }
  101. ctx.Lang = lang
  102. if config.IsInit {
  103. user := cast.ToString(session.Instance.Get(ctx, "user"))
  104. if user != "" {
  105. _ = json.Unmarshal([]byte(user), &ctx.UserInfo)
  106. }
  107. if ctx.UserInfo == nil || ctx.UserInfo.ID == 0 {
  108. if r.URL.Path != "/api/ping" && r.URL.Path != "/api/login" {
  109. response.NewErrorResponse(response.NeedLogin, i18n.GetText(ctx.Lang, "login_exp"), "").FPrint(w)
  110. return
  111. }
  112. }
  113. } else if r.URL.Path != "/api/setup" {
  114. response.NewErrorResponse(response.NeedSetup, "", "").FPrint(w)
  115. return
  116. }
  117. h(ctx, w, r)
  118. }
  119. }