auth.go 826 B

123456789101112131415161718192021222324252627282930
  1. package auth
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "quickip/internal/config"
  6. "quickip/internal/model"
  7. )
  8. func Middleware(cfg config.Config, next http.Handler) http.Handler {
  9. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  10. password := r.Header.Get("X-Admin-Password")
  11. if password == "" {
  12. writeJSON(w, http.StatusUnauthorized, model.APIResponse{Code: 1001, Message: "缺少密码", Data: nil})
  13. return
  14. }
  15. if password != cfg.AdminPassword {
  16. writeJSON(w, http.StatusUnauthorized, model.APIResponse{Code: 1002, Message: "密码错误", Data: nil})
  17. return
  18. }
  19. next.ServeHTTP(w, r)
  20. })
  21. }
  22. func writeJSON(w http.ResponseWriter, status int, payload model.APIResponse) {
  23. w.Header().Set("Content-Type", "application/json")
  24. w.WriteHeader(status)
  25. _ = json.NewEncoder(w).Encode(payload)
  26. }