123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- package config
- import (
- "encoding/json"
- "fmt"
- "io/ioutil"
- "os"
- "strings"
- )
- func initBannedIP(serverFolder string) BannedIP {
- jsonFile, err := os.Open(serverFolder + "/banned-ips.json")
- if err != nil {
- fmt.Println(err)
- }
- byte, _ := ioutil.ReadAll(jsonFile)
- var dataArray BannedIP
- json.Unmarshal(byte, &dataArray)
- return dataArray
- }
- //ReadAllBannedIPs is exported function
- func (mch *Handler) ReadAllBannedIPs() BannedIP {
- return mch.bannedIPs
- }
- //WriteBannedIP is exported function
- func (mch *Handler) WriteBannedIP(IP string, Created string, Source string, Expires string, Reason string) bool {
- mch.reloadBanIP() //ensure that everything updated.
- newItem := BannedIP{}
- newItem = append(newItem, struct {
- IP string `json:"ip"`
- Created string `json:"created"`
- Source string `json:"source"`
- Expires string `json:"expires"`
- Reason string `json:"reason"`
- }{IP, Created, Source, Expires, Reason})
- mch.bannedIPs = append(mch.bannedIPs, newItem...)
- mch.SaveAllBannedIPs() //save it
- return true
- }
- //ReadBannedIP is exported function
- func (mch *Handler) ReadBannedIP(search string, field string) BannedIP {
- var list BannedIP
- for _, item := range mch.bannedIPs {
- fieldValue := ""
- switch strings.ToLower(field) {
- case "ip":
- fieldValue = item.IP
- case "created":
- fieldValue = item.Created
- case "source":
- fieldValue = item.Source
- case "expires":
- fieldValue = item.Expires
- case "reason":
- fieldValue = item.Reason
- default:
- fieldValue = ""
- }
- if fieldValue == search {
- list = append(list, item)
- }
- }
- return list
- }
- //RemoveBannedIP is exported function
- func (mch *Handler) RemoveBannedIP(search string, field string) bool {
- mch.reloadBanIP() //ensure that everything updated.
- for i, item := range mch.bannedIPs {
- fieldValue := ""
- switch strings.ToLower(field) {
- case "ip":
- fieldValue = item.IP
- case "created":
- fieldValue = item.Created
- case "source":
- fieldValue = item.Source
- case "expires":
- fieldValue = item.Expires
- case "reason":
- fieldValue = item.Reason
- default:
- fieldValue = ""
- }
- if fieldValue == search {
- if len(mch.bannedIPs)-1 != i {
- mch.bannedIPs = append(mch.bannedIPs[:i], mch.bannedIPs[i+1:]...)
- } else {
- // if it is the last item, just remove it
- mch.bannedIPs = mch.bannedIPs[:i]
- }
- }
- }
- mch.SaveAllBannedIPs()
- return true
- }
- //SaveAllBannedIPs is exported function
- func (mch *Handler) SaveAllBannedIPs() bool {
- JSON, _ := json.Marshal(mch.bannedIPs)
- err := ioutil.WriteFile(mch.serverFolder+"/banned-ips.json", JSON, 0777)
- if err != nil {
- fmt.Println(err)
- }
- return true
- }
|