banIP.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package config
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "strings"
  8. )
  9. func initBannedIP(serverFolder string) BannedIP {
  10. jsonFile, err := os.Open(serverFolder + "banned-ips.json")
  11. if err != nil {
  12. fmt.Println(err)
  13. }
  14. byte, _ := ioutil.ReadAll(jsonFile)
  15. var dataArray BannedIP
  16. json.Unmarshal(byte, &dataArray)
  17. return dataArray
  18. }
  19. //ReadAllBannedIPs is exported function
  20. func (mch *Handler) ReadAllBannedIPs() BannedIP {
  21. return mch.bannedIPs
  22. }
  23. //WriteBannedIP is exported function
  24. func (mch *Handler) WriteBannedIP(IP string, Created string, Source string, Expires string, Reason string) bool {
  25. newItem := BannedIP{}
  26. newItem = append(newItem, struct {
  27. IP string `json:"ip"`
  28. Created string `json:"created"`
  29. Source string `json:"source"`
  30. Expires string `json:"expires"`
  31. Reason string `json:"reason"`
  32. }{IP, Created, Source, Expires, Reason})
  33. mch.bannedIPs = append(mch.bannedIPs, newItem...)
  34. return true
  35. }
  36. //ReadBannedIP is exported function
  37. func (mch *Handler) ReadBannedIP(search string, field string) BannedIP {
  38. var list BannedIP
  39. for _, item := range mch.bannedIPs {
  40. fieldValue := ""
  41. switch strings.ToLower(field) {
  42. case "ip":
  43. fieldValue = item.IP
  44. case "created":
  45. fieldValue = item.Created
  46. case "source":
  47. fieldValue = item.Source
  48. case "expires":
  49. fieldValue = item.Expires
  50. case "reason":
  51. fieldValue = item.Reason
  52. default:
  53. fieldValue = ""
  54. }
  55. if fieldValue == search {
  56. list = append(list, item)
  57. }
  58. }
  59. return list
  60. }
  61. //RemoveBannedIP is exported function
  62. func (mch *Handler) RemoveBannedIP(search string, field string) bool {
  63. var list BannedIP
  64. for i, item := range mch.bannedIPs {
  65. fieldValue := ""
  66. switch strings.ToLower(field) {
  67. case "ip":
  68. fieldValue = item.IP
  69. case "created":
  70. fieldValue = item.Created
  71. case "source":
  72. fieldValue = item.Source
  73. case "expires":
  74. fieldValue = item.Expires
  75. case "reason":
  76. fieldValue = item.Reason
  77. default:
  78. fieldValue = ""
  79. }
  80. if fieldValue == search {
  81. list = append(list[:i], list[i+1])
  82. }
  83. }
  84. return true
  85. }
  86. //SaveAllBannedIPs is exported function
  87. func (mch *Handler) SaveAllBannedIPs() bool {
  88. JSON, _ := json.Marshal(mch.bannedIPs)
  89. err := ioutil.WriteFile(mch.serverFolder+"/banned-ips.json", JSON, 0777)
  90. if err != nil {
  91. fmt.Println(err)
  92. }
  93. return true
  94. }