whiteList.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package middleware
  2. import (
  3. "fmt"
  4. "log"
  5. "net"
  6. "net/http"
  7. "strings"
  8. )
  9. // WhiteListCheck 用于 IP 白名单验证的中间件函数
  10. func WhiteListCheck(allowedIPs []string) func(http.HandlerFunc) http.HandlerFunc {
  11. ipNets, err := parseIPNets(allowedIPs)
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. return func(next http.HandlerFunc) http.HandlerFunc {
  16. return func(w http.ResponseWriter, r *http.Request) {
  17. ip := getClientIP(r)
  18. if !isAllowedIP(ip, ipNets) {
  19. http.Error(w, "Forbidden", http.StatusForbidden)
  20. return
  21. }
  22. next.ServeHTTP(w, r)
  23. }
  24. }
  25. }
  26. //func WhiteListMiddleware(allowedIPs []string) func(http.HandlerFunc) http.HandlerFunc {
  27. // return func(next http.HandlerFunc) http.HandlerFunc {
  28. // return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  29. // ip := getClientIP(r)
  30. // if !isAllowedIP(ip, allowedIPs) {
  31. // http.Error(w, "Forbidden", http.StatusForbidden)
  32. // return
  33. // }
  34. // next.ServeHTTP(w, r)
  35. // })
  36. // }
  37. //}
  38. // 获取客户端IP地址
  39. func getClientIP(r *http.Request) string {
  40. forwardedFor := r.Header.Get("X-Forwarded-For")
  41. if forwardedFor != "" {
  42. ips := strings.Split(forwardedFor, ",")
  43. if len(ips) > 0 {
  44. return ips[0]
  45. }
  46. }
  47. return r.RemoteAddr
  48. }
  49. // 判断IP是否在白名单中
  50. func isAllowedIP(ip string, ipNets []*net.IPNet) bool {
  51. clientIP := net.ParseIP(ip)
  52. fmt.Println("clientIP:", clientIP)
  53. for _, ipNet := range ipNets {
  54. if ipNet.Contains(clientIP) {
  55. return true
  56. }
  57. }
  58. return false
  59. }
  60. //func isAllowedIP(ip string, whitelist []string) bool {
  61. // for _, allowedIP := range whitelist {
  62. // if ip == allowedIP {
  63. // return true
  64. // }
  65. // }
  66. // return false
  67. //}
  68. func parseIPNets(allowedIPs []string) ([]*net.IPNet, error) {
  69. ipNets := make([]*net.IPNet, 0, len(allowedIPs))
  70. for _, ipStr := range allowedIPs {
  71. _, ipNet, err := net.ParseCIDR(ipStr)
  72. if err != nil {
  73. return nil, err
  74. }
  75. ipNets = append(ipNets, ipNet)
  76. }
  77. fmt.Println("ipNets:", ipNets)
  78. return ipNets, nil
  79. }