dhcp.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package backend
  2. import (
  3. "github.com/glebarez/sqlite"
  4. "gorm.io/gorm"
  5. "os"
  6. "path/filepath"
  7. )
  8. type Dhcp struct {
  9. Id int `json:"id" gorm:"id"` // ID
  10. MACAddress string `json:"mac_address" gorm:"mac_address"` // MAC地址
  11. IPAddress string `json:"ip_address" gorm:"ip_address"` // IP地址
  12. SubnetMask string `json:"subnet_mask" gorm:"subnet_mask"` // 子网掩码
  13. DefaultGateway string `json:"default_gateway" gorm:"default_gateway"` // 默认网关
  14. NameServers []string `json:"name_servers" gorm:"name_servers"` // DNS服务器
  15. DomainName string `json:"domain_name" gorm:"domain_name"` // 域名
  16. BroadcastAddress string `json:"broadcast_address" gorm:"broadcast_address"` // 广播地址
  17. NTPServers []string `json:"ntp_servers" gorm:"ntp_servers"` // NTP服务器
  18. VLANID string `json:"vlan_id" gorm:"vlan_id"` // VLAN ID
  19. LeaseTime uint32 `json:"lease_time" gorm:"lease_time"` // 租约
  20. DomainSearch []string `json:"domain_search" gorm:"domain_search"` // 域名搜索
  21. ServerIP string `json:"server_ip" gorm:"server_ip"` // 服务器IP
  22. }
  23. // 定义数据库指针
  24. var db *gorm.DB
  25. // 初始化数据库指针
  26. func InitDB() {
  27. executablePath, err := os.Executable()
  28. if err != nil {
  29. panic(err)
  30. }
  31. dbPath := filepath.Join(filepath.Dir(executablePath), "dhcp.db")
  32. db, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
  33. if err != nil {
  34. panic(err)
  35. }
  36. db.AutoMigrate(&Dhcp{})
  37. }
  38. func AddDhcp(dhcp Dhcp) error {
  39. var dp Dhcp
  40. tx := db.Model(&Dhcp{}).Where("mac_address = ?", dhcp.MACAddress).First(dp)
  41. if tx.Error != nil {
  42. return tx.Error
  43. }
  44. if dp.Id == 0 {
  45. tx = db.Create(&dhcp)
  46. } else {
  47. tx = db.Model(&Dhcp{}).Where("mac_address = ?", dhcp.MACAddress).Updates(dhcp)
  48. }
  49. if tx.Error != nil {
  50. return tx.Error
  51. }
  52. return nil
  53. }
  54. func GetDhcp(macAddress string) (Dhcp, error) {
  55. var dhcp Dhcp
  56. tx := db.Model(&Dhcp{}).Where("mac_address = ?", macAddress).First(&dhcp)
  57. if tx.Error != nil {
  58. return dhcp, tx.Error
  59. }
  60. return dhcp, nil
  61. }
  62. func DeleteDhcp(macAddress string) error {
  63. tx := db.Model(&Dhcp{}).Where("mac_address = ?", macAddress).Delete(&Dhcp{})
  64. if tx.Error != nil {
  65. return tx.Error
  66. }
  67. return nil
  68. }
  69. func UpdateDhcp(dhcp Dhcp) error {
  70. tx := db.Model(&Dhcp{}).Where("mac_address = ?", dhcp.MACAddress).Updates(dhcp)
  71. if tx.Error != nil {
  72. return tx.Error
  73. }
  74. return nil
  75. }