From d57d69952fcdd6e4c5bbf7c0b4a345ebbc3e5cb0 Mon Sep 17 00:00:00 2001 From: Cody Lee Date: Thu, 27 Jul 2023 08:38:41 -0500 Subject: [PATCH 1/4] adds linting rules and addresses lint report ignore lints that would cause breaking changes --- .golangci.yaml | 27 ++++++++ alarms.go | 26 ++++---- anomalies.go | 4 +- clients.go | 28 ++++---- devices.go | 1 + devmgr.go | 7 +- dpi.go | 10 +-- events.go | 50 +++++++------- ids.go | 38 +++++------ mocks/mock_client.go | 152 ++++++++++++++++++++++++++++++++++++------- mocks/mock_server.go | 45 ++++++++++++- networks.go | 5 +- pdu.go | 52 +++++++-------- pdu_test.go | 5 +- site.go | 19 +++--- types.go | 38 ++++++----- uap.go | 92 +++++++++++++------------- udm.go | 78 +++++++++++----------- unifi.go | 3 +- users.go | 14 ++-- usg.go | 58 ++++++++--------- usw.go | 4 +- uxg.go | 30 ++++----- 23 files changed, 488 insertions(+), 298 deletions(-) create mode 100644 .golangci.yaml diff --git a/.golangci.yaml b/.golangci.yaml new file mode 100644 index 0000000..d5c75e1 --- /dev/null +++ b/.golangci.yaml @@ -0,0 +1,27 @@ +run: + timeout: 3m + +linters: + enable: + - wsl + - nlreturn + - tagalign + - revive + - testpackage + - errcheck + - gosimple + - govet + - ineffassign + - staticcheck + - unused + +output: + sort-results: true + +issues: + # disable the default limit so we see everything + max-same-issues: 0 + max-issues-per-linter: 0 + + # default enable fix where the linter supports + fix: true diff --git a/alarms.go b/alarms.go index 46549bf..77c5df6 100644 --- a/alarms.go +++ b/alarms.go @@ -8,44 +8,44 @@ import ( type Alarm struct { Archived FlexBool `json:"archived"` - DestPort int `json:"dest_port" fake:"{port}"` - SrcPort int `json:"src_port" fake:"{port}"` + DestPort int `fake:"{port}" json:"dest_port"` + SrcPort int `fake:"{port}" json:"src_port"` FlowID int64 `json:"flow_id"` InnerAlertGID int64 `json:"inner_alert_gid"` InnerAlertRev int64 `json:"inner_alert_rev"` InnerAlertSeverity int64 `json:"inner_alert_severity"` InnerAlertSignatureID int64 `json:"inner_alert_signature_id"` - Time int64 `json:"time" fake:"{timestamp}"` - Timestamp int64 `json:"timestamp" fake:"{timestamp}"` + Time int64 `fake:"{timestamp}" json:"time"` + Timestamp int64 `fake:"{timestamp}" json:"timestamp"` Datetime time.Time `json:"datetime"` HandledTime time.Time `json:"handled_time,omitempty"` AppProto string `json:"app_proto,omitempty"` Catname string `json:"catname"` - DestIP string `json:"dest_ip" fake:"{ipv4address}"` - DstMAC string `json:"dst_mac" fake:"{macaddress}"` + DestIP string `fake:"{ipv4address}" json:"dest_ip"` + DstMAC string `fake:"{macaddress}" json:"dst_mac"` DstIPASN string `json:"dstipASN,omitempty"` DstIPCountry string `json:"dstipCountry,omitempty"` EventType string `json:"event_type"` HandledAdminID string `json:"handled_admin_id,omitempty"` Host string `json:"host"` - ID string `json:"_id" fake:"{uuid}"` - InIface string `json:"in_iface" fake:"{randomstring:[eth0,eth1,lan1,wan1,wan2]}"` + ID string `fake:"{uuid}" json:"_id"` + InIface string `fake:"{randomstring:[eth0,eth1,lan1,wan1,wan2]}" json:"in_iface"` InnerAlertAction string `json:"inner_alert_action"` InnerAlertCategory string `json:"inner_alert_category"` InnerAlertSignature string `json:"inner_alert_signature"` Key string `json:"key"` - Msg string `json:"msg" fake:"{sentence:5}"` + Msg string `fake:"{sentence:5}" json:"msg"` Proto string `json:"proto"` - SiteID string `json:"site_id" fake:"{uuid}"` + SiteID string `fake:"{uuid}" json:"site_id"` SiteName string `json:"-"` SourceName string `json:"-"` - SrcIP string `json:"src_ip" fake:"{ipv4address}"` + SrcIP string `fake:"{ipv4address}" json:"src_ip"` SrcIPASN string `json:"srcipASN,omitempty"` SrcIPCountry string `json:"srcipCountry,omitempty"` - SrcMAC string `json:"src_mac" fake:"{macaddress}"` + SrcMAC string `fake:"{macaddress}" json:"src_mac"` Subsystem string `json:"subsystem"` UniqueAlertID string `json:"unique_alertid"` - USGIP string `json:"usgip" fake:"{ipv4address}"` + USGIP string `fake:"{ipv4address}" json:"usgip"` USGIPASN string `json:"usgipASN"` USGIPCountry string `json:"usgipCountry"` TxID FlexInt `json:"tx_id,omitempty"` diff --git a/anomalies.go b/anomalies.go index 28dfa84..9931221 100644 --- a/anomalies.go +++ b/anomalies.go @@ -11,8 +11,8 @@ import ( // anomaly is the type UniFi returns, but not the type this library returns. type anomaly struct { Anomaly string `json:"anomaly"` - MAC string `json:"mac" fake:"{macaddress}"` - Timestamps []int64 `json:"timestamps" fake:"{timestamps}"` + MAC string `fake:"{macaddress}" json:"mac"` + Timestamps []int64 `fake:"{timestamps}" json:"timestamps"` } // Anomaly is the reformatted data type that this library returns. diff --git a/clients.go b/clients.go index e23dec0..e64785f 100644 --- a/clients.go +++ b/clients.go @@ -67,11 +67,11 @@ func (u *Unifi) GetClientsDPI(sites []*Site) ([]*DPITable, error) { type Client struct { SourceName string `json:"-"` Anomalies FlexInt `json:"anomalies,omitempty"` - ApMac string `json:"ap_mac" fake:"{macaddress}"` + ApMac string `fake:"{macaddress}" json:"ap_mac"` ApName string `json:"-"` AssocTime FlexInt `json:"assoc_time"` Blocked bool `json:"blocked,omitempty"` - Bssid string `json:"bssid" fake:"{macaddress}"` + Bssid string `fake:"{macaddress}" json:"bssid"` BytesR FlexInt `json:"bytes-r"` Ccq FlexInt `json:"ccq"` Channel FlexInt `json:"channel"` @@ -81,14 +81,14 @@ type Client struct { DevVendor FlexInt `json:"dev_vendor,omitempty"` DhcpendTime FlexInt `json:"dhcpend_time,omitempty"` Satisfaction FlexInt `json:"satisfaction,omitempty"` - Essid string `json:"essid" fake:"{macaddress}"` + Essid string `fake:"{macaddress}" json:"essid"` FirstSeen FlexInt `json:"first_seen"` - FixedIP string `json:"fixed_ip" fake:"{ipv4address}"` - GwMac string `json:"gw_mac" fake:"{macaddress}"` + FixedIP string `fake:"{ipv4address}" json:"fixed_ip"` + GwMac string `fake:"{macaddress}" json:"gw_mac"` GwName string `json:"-"` Hostname string `json:"hostname"` - ID string `json:"_id" fake:"{uuid}"` - IP string `json:"ip" fake:"{ipv4address}"` + ID string `fake:"{uuid}" json:"_id"` + IP string `fake:"{ipv4address}" json:"ip"` IdleTime FlexInt `json:"idle_time"` Is11R FlexBool `json:"is_11r"` IsGuest FlexBool `json:"is_guest"` @@ -101,12 +101,12 @@ type Client struct { LastSeenByUGW FlexInt `json:"_last_seen_by_ugw"` LastSeenByUSW FlexInt `json:"_last_seen_by_usw"` LatestAssocTime FlexInt `json:"latest_assoc_time"` - Mac string `json:"mac" fake:"{macaddress}"` + Mac string `fake:"{macaddress}" json:"mac"` Name string `json:"name"` Network string `json:"network"` - NetworkID string `json:"network_id" fake:"{uuid}"` + NetworkID string `fake:"{uuid}" json:"network_id"` Noise FlexInt `json:"noise"` - Note string `json:"note" fake:"{sentence 20}"` + Note string `fake:"{sentence 20}" json:"note"` Noted FlexBool `json:"noted"` OsClass FlexInt `json:"os_class"` OsName FlexInt `json:"os_name"` @@ -124,10 +124,10 @@ type Client struct { RxPackets FlexInt `json:"rx_packets"` RxRate FlexInt `json:"rx_rate"` Signal FlexInt `json:"signal"` - SiteID string `json:"site_id" fake:"{uuid}"` + SiteID string `fake:"{uuid}" json:"site_id"` SiteName string `json:"-"` SwDepth int `json:"sw_depth"` - SwMac string `json:"sw_mac" fake:"{macaddress}"` + SwMac string `fake:"{macaddress}" json:"sw_mac"` SwName string `json:"-"` SwPort FlexInt `json:"sw_port"` TxBytes FlexInt `json:"tx_bytes"` @@ -141,8 +141,8 @@ type Client struct { UptimeByUGW FlexInt `json:"_uptime_by_ugw"` UptimeByUSW FlexInt `json:"_uptime_by_usw"` UseFixedIP FlexBool `json:"use_fixedip"` - UserGroupID string `json:"usergroup_id" fake:"{uuid}"` - UserID string `json:"user_id" fake:"{uuid}"` + UserGroupID string `fake:"{uuid}" json:"usergroup_id"` + UserID string `fake:"{uuid}" json:"user_id"` Vlan FlexInt `json:"vlan"` WifiTxAttempts FlexInt `json:"wifi_tx_attempts"` WiredRxBytes FlexInt `json:"wired-rx_bytes"` diff --git a/devices.go b/devices.go index f35b3f6..0421703 100644 --- a/devices.go +++ b/devices.go @@ -116,6 +116,7 @@ func (u *Unifi) parseDevices(data []json.RawMessage, site *Site) *Devices { var o minimalUnmarshalInfo if u.unmarshalDevice("map", r, &o) != nil { u.ErrorLog("unknown asset type - cannot find asset type in payload - skipping") + continue } diff --git a/devmgr.go b/devmgr.go index 97b44bd..d31d663 100644 --- a/devmgr.go +++ b/devmgr.go @@ -27,9 +27,9 @@ const ( // devMgrCmd is the type marshalled and sent to APIDevMgrPath. type devMgrCmd struct { Cmd string `json:"cmd"` // Required. - Mac string `json:"mac" fake:"{macaddress}"` // Device MAC (required for most, but not all). - URL string `json:"url,omitempty" fake:"{url}"` // External Upgrade only. - Inform string `json:"inform_url,omitempty" fake:"{url}"` // Migration only. + Mac string `fake:"{macaddress}" json:"mac"` // Device MAC (required for most, but not all). + URL string `fake:"{url}" json:"url,omitempty"` // External Upgrade only. + Inform string `fake:"{url}" json:"inform_url,omitempty"` // Migration only. Port int `json:"port_idx,omitempty"` // Power Cycle only. } @@ -51,6 +51,7 @@ func (s *Site) devMgrCommandReply(cmd *devMgrCmd) ([]byte, error) { // devMgrCommandSimple is for commands with no return value. func (s *Site) devMgrCommandSimple(cmd *devMgrCmd) error { _, err := s.devMgrCommandReply(cmd) + return err } diff --git a/dpi.go b/dpi.go index c55ea73..b61a88b 100644 --- a/dpi.go +++ b/dpi.go @@ -7,9 +7,9 @@ type DPITable struct { SourceName string `json:"-"` SiteName string `json:"-"` Name string `json:"-"` - MAC string `json:"mac" fake:"{macaddress}"` - ByCat []DPIData `json:"by_cat" fakesize:"5"` - ByApp []DPIData `json:"by_app" fakesize:"5"` + MAC string `fake:"{macaddress}" json:"mac"` + ByCat []DPIData `fakesize:"5" json:"by_cat"` + ByApp []DPIData `fakesize:"5" json:"by_app"` LastUpdated FlexInt `json:"last_updated"` } @@ -21,13 +21,13 @@ type DPIData struct { TxBytes FlexInt `json:"tx_bytes"` RxPackets FlexInt `json:"rx_packets"` TxPackets FlexInt `json:"tx_packets"` - Clients []*DPIClient `json:"clients,omitempty" fakesize:"5"` + Clients []*DPIClient `fakesize:"5" json:"clients,omitempty"` KnownClients FlexInt `json:"known_clients,omitempty"` } // DPIClient data is sometimes included in ByApp output. type DPIClient struct { - Mac string `json:"mac" fake:"{macaddress}"` + Mac string `fake:"{macaddress}" json:"mac"` RxBytes FlexInt `json:"rx_bytes"` TxBytes FlexInt `json:"tx_bytes"` RxPackets FlexInt `json:"rx_packets"` diff --git a/events.go b/events.go index 6bd063c..3ac86c8 100644 --- a/events.go +++ b/events.go @@ -73,8 +73,8 @@ func (u *Unifi) GetSiteEvents(site *Site, hours time.Duration) ([]*Event, error) // API Path: /api/s/default/stat/event. type Event struct { IsAdmin FlexBool `json:"is_admin"` - DestPort int `json:"dest_port" fake:"{port}"` - SrcPort int `json:"src_port" fake:"{port}"` + DestPort int `fake:"{port}" json:"dest_port"` + SrcPort int `fake:"{port}" json:"src_port"` Bytes FlexInt `json:"bytes"` Duration FlexInt `json:"duration"` FlowID FlexInt `json:"flow_id"` @@ -85,8 +85,8 @@ type Event struct { Channel FlexInt `json:"channel"` ChannelFrom FlexInt `json:"channel_from"` ChannelTo FlexInt `json:"channel_to"` - Time int64 `json:"time" fake:"{timestamp}"` - Timestamp int64 `json:"timestamp" fake:"{timestamp}"` + Time int64 `fake:"{timestamp}" json:"time"` + Timestamp int64 `fake:"{timestamp}" json:"timestamp"` Datetime time.Time `json:"datetime"` Admin string `json:"admin"` Ap string `json:"ap"` @@ -95,43 +95,43 @@ type Event struct { ApTo string `json:"ap_to"` AppProto string `json:"app_proto"` Catname string `json:"catname"` - DestIP string `json:"dest_ip" fake:"{ipv4address}"` - DstMAC string `json:"dst_mac" fake:"{macaddress}"` + DestIP string `fake:"{ipv4address}" json:"dest_ip"` + DstMAC string `fake:"{macaddress}" json:"dst_mac"` EventType string `json:"event_type"` Guest string `json:"guest"` Gw string `json:"gw"` GwName string `json:"gw_name"` Host string `json:"host"` Hostname string `json:"hostname"` - ID string `json:"_id" fake:"{uuid}"` - IP string `json:"ip" fake:"{ipv4address}"` + ID string `fake:"{uuid}" json:"_id"` + IP string `fake:"{ipv4address}" json:"ip"` InIface string `json:"in_iface"` InnerAlertAction string `json:"inner_alert_action"` InnerAlertCategory string `json:"inner_alert_category"` InnerAlertSignature string `json:"inner_alert_signature"` - Key string `json:"key" fake:"{uuid}"` - Msg string `json:"msg" fake:"{buzzword}"` + Key string `fake:"{uuid}" json:"key"` + Msg string `fake:"{buzzword}" json:"msg"` Network string `json:"network"` Proto string `json:"proto"` Radio string `json:"radio"` RadioFrom string `json:"radio_from"` RadioTo string `json:"radio_to"` - SiteID string `json:"site_id" fake:"{}"` + SiteID string `fake:"{}" json:"site_id"` SiteName string `json:"-"` SourceName string `json:"-"` - SrcIP string `json:"src_ip" fake:"{ipv4address}"` - SrcMAC string `json:"src_mac" fake:"{macaddress}"` - SrcIPASN string `json:"srcipASN" fake:"{address}"` - SrcIPCountry string `json:"srcipCountry" fake:"{country}"` - SSID string `json:"ssid" fake:"{macaddress}"` + SrcIP string `fake:"{ipv4address}" json:"src_ip"` + SrcMAC string `fake:"{macaddress}" json:"src_mac"` + SrcIPASN string `fake:"{address}" json:"srcipASN"` + SrcIPCountry string `fake:"{country}" json:"srcipCountry"` + SSID string `fake:"{macaddress}" json:"ssid"` Subsystem string `json:"subsystem"` Sw string `json:"sw"` SwName string `json:"sw_name"` UniqueAlertID string `json:"unique_alertid"` User string `json:"user"` - USGIP string `json:"usgip" fake:"{ipv4address}"` - USGIPASN string `json:"usgipASN" fake:"{address}"` - USGIPCountry string `json:"usgipCountry" fake:"{country}"` + USGIP string `fake:"{ipv4address}" json:"usgip"` + USGIPASN string `fake:"{address}" json:"usgipASN"` + USGIPCountry string `fake:"{country}" json:"usgipCountry"` DestIPGeo IPGeo `json:"dstipGeo"` SourceIPGeo IPGeo `json:"srcipGeo"` USGIPGeo IPGeo `json:"usgipGeo"` @@ -141,13 +141,13 @@ type Event struct { // One for source, one for dest and one for the USG location. type IPGeo struct { Asn int64 `json:"asn"` - Latitude float64 `json:"latitude" fake:"{latitude}"` - Longitude float64 `json:"longitude" fake:"{longitude}"` - City string `json:"city" fake:"{city}"` + Latitude float64 `fake:"{latitude}" json:"latitude"` + Longitude float64 `fake:"{longitude}" json:"longitude"` + City string `fake:"{city}" json:"city"` ContinentCode string `json:"continent_code"` - CountryCode string `json:"country_code" fake:"{countryabr}"` - CountryName string `json:"country_name" fake:"{country}"` - Organization string `json:"organization" fake:"{company}"` + CountryCode string `fake:"{countryabr}" json:"country_code"` + CountryName string `fake:"{country}" json:"country_name"` + Organization string `fake:"{company}" json:"organization"` } // Events satisfied the sort.Interface. diff --git a/ids.go b/ids.go index f274f84..dcf74e5 100644 --- a/ids.go +++ b/ids.go @@ -10,44 +10,44 @@ import ( // IDS holds an Intrusion Prevention System Event. type IDS struct { Archived FlexBool `json:"archived"` - DestPort int `json:"dest_port,omitempty" fake:"{port}"` - SrcPort int `json:"src_port,omitempty" fake:"{port}"` + DestPort int `fake:"{port}" json:"dest_port,omitempty"` + SrcPort int `fake:"{port}" json:"src_port,omitempty"` FlowID int64 `json:"flow_id"` InnerAlertRev int64 `json:"inner_alert_rev"` InnerAlertSeverity int64 `json:"inner_alert_severity"` InnerAlertGID int64 `json:"inner_alert_gid"` InnerAlertSignatureID int64 `json:"inner_alert_signature_id"` - Time int64 `json:"time" fake:"{timestamp}"` - Timestamp int64 `json:"timestamp" fake:"{timestamp}"` + Time int64 `fake:"{timestamp}" json:"time"` + Timestamp int64 `fake:"{timestamp}" json:"timestamp"` Datetime time.Time `json:"datetime"` AppProto string `json:"app_proto,omitempty"` Catname string `json:"catname"` - DestIP string `json:"dest_ip" fake:"{ipv4address}"` - DstMAC string `json:"dst_mac" fake:"{macaddress}"` - DstIPASN string `json:"dstipASN" fake:"{address}"` - DstIPCountry string `json:"dstipCountry" fake:"{country}"` + DestIP string `fake:"{ipv4address}" json:"dest_ip"` + DstMAC string `fake:"{macaddress}" json:"dst_mac"` + DstIPASN string `fake:"{address}" json:"dstipASN"` + DstIPCountry string `fake:"{country}" json:"dstipCountry"` EventType string `json:"event_type"` Host string `json:"host"` - ID string `json:"_id" fake:"{uuid}"` + ID string `fake:"{uuid}" json:"_id"` InIface string `json:"in_iface"` InnerAlertAction string `json:"inner_alert_action"` InnerAlertCategory string `json:"inner_alert_category"` InnerAlertSignature string `json:"inner_alert_signature"` - Key string `json:"key" fake:"{uuid}"` - Msg string `json:"msg" fake:"{buzzword}"` + Key string `fake:"{uuid}" json:"key"` + Msg string `fake:"{buzzword}" json:"msg"` Proto string `json:"proto"` - SiteID string `json:"site_id" fake:"{uuid}"` + SiteID string `fake:"{uuid}" json:"site_id"` SiteName string `json:"-"` SourceName string `json:"-"` - SrcIP string `json:"src_ip" fake:"{ipv4address}"` - SrcIPASN string `json:"srcipASN" fake:"{address}"` - SrcIPCountry string `json:"srcipCountry" fake:"{country}"` - SrcMAC string `json:"src_mac" fake:"{macaddress}"` + SrcIP string `fake:"{ipv4address}" json:"src_ip"` + SrcIPASN string `fake:"{address}" json:"srcipASN"` + SrcIPCountry string `fake:"{country}" json:"srcipCountry"` + SrcMAC string `fake:"{macaddress}" json:"src_mac"` Subsystem string `json:"subsystem"` UniqueAlertID string `json:"unique_alertid"` - USGIP string `json:"usgip" fake:"{ipv4address}"` - USGIPASN string `json:"usgipASN" fake:"{address}"` - USGIPCountry string `json:"usgipCountry" fake:"{country}"` + USGIP string `fake:"{ipv4address}" json:"usgip"` + USGIPASN string `fake:"{address}" json:"usgipASN"` + USGIPCountry string `fake:"{country}" json:"usgipCountry"` DestIPGeo IPGeo `json:"dstipGeo"` SourceIPGeo IPGeo `json:"srcipGeo"` USGIPGeo IPGeo `json:"usgipGeo"` diff --git a/mocks/mock_client.go b/mocks/mock_client.go index a0f7a2d..70f14b9 100644 --- a/mocks/mock_client.go +++ b/mocks/mock_client.go @@ -17,260 +17,342 @@ var _ unifi.UnifiClient = &MockUnifi{} func NewMockUnifi() *MockUnifi { return &MockUnifi{} - } // GetAlarms returns Alarms for a list of Sites. -func (m *MockUnifi) GetAlarms(sites []*unifi.Site) ([]*unifi.Alarm, error) { +func (m *MockUnifi) GetAlarms(_ []*unifi.Site) ([]*unifi.Alarm, error) { qty := rand.Intn(5) + 1 alarms := make([]*unifi.Alarm, qty) + for i := 0; i < qty; i++ { var a unifi.Alarm + err := gofakeit.Struct(&a) + if err != nil { return alarms, err } + alarms[i] = &a } + return alarms, nil } // GetAlarmsSite retreives the Alarms for a single Site. -func (m *MockUnifi) GetAlarmsSite(site *unifi.Site) ([]*unifi.Alarm, error) { +func (m *MockUnifi) GetAlarmsSite(_ *unifi.Site) ([]*unifi.Alarm, error) { qty := rand.Intn(5) + 1 alarms := make([]*unifi.Alarm, qty) + for i := 0; i < qty; i++ { var a unifi.Alarm + err := gofakeit.Struct(&a) + if err != nil { return alarms, err } + alarms[i] = &a } + return alarms, nil } // GetAnomalies returns Anomalies for a list of Sites. -func (m *MockUnifi) GetAnomalies(sites []*unifi.Site, timeRange ...time.Time) ([]*unifi.Anomaly, error) { +func (m *MockUnifi) GetAnomalies(_ []*unifi.Site, _ ...time.Time) ([]*unifi.Anomaly, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.Anomaly, qty) + for i := 0; i < qty; i++ { var a unifi.Anomaly + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } // GetAnomaliesSite retreives the Anomalies for a single Site. -func (m *MockUnifi) GetAnomaliesSite(site *unifi.Site, timeRange ...time.Time) ([]*unifi.Anomaly, error) { +func (m *MockUnifi) GetAnomaliesSite(_ *unifi.Site, _ ...time.Time) ([]*unifi.Anomaly, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.Anomaly, qty) + for i := 0; i < qty; i++ { var a unifi.Anomaly + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } // GetClients returns a response full of clients' data from the UniFi Controller. -func (m *MockUnifi) GetClients(sites []*unifi.Site) ([]*unifi.Client, error) { +func (m *MockUnifi) GetClients(_ []*unifi.Site) ([]*unifi.Client, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.Client, qty) + for i := 0; i < qty; i++ { var a unifi.Client + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } // GetClientsDPI garners dpi data for clients. -func (m *MockUnifi) GetClientsDPI(sites []*unifi.Site) ([]*unifi.DPITable, error) { +func (m *MockUnifi) GetClientsDPI(_ []*unifi.Site) ([]*unifi.DPITable, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.DPITable, qty) + for i := 0; i < qty; i++ { var a unifi.DPITable + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } // GetDevices returns a response full of devices' data from the UniFi Controller. -func (m *MockUnifi) GetDevices(sites []*unifi.Site) (*unifi.Devices, error) { +func (m *MockUnifi) GetDevices(_ []*unifi.Site) (*unifi.Devices, error) { var d unifi.Devices + err := gofakeit.Struct(&d) + if err != nil { return nil, err } + return &d, nil } // GetUSWs returns all switches, an error, or nil if there are no switches. -func (m *MockUnifi) GetUSWs(site *unifi.Site) ([]*unifi.USW, error) { +func (m *MockUnifi) GetUSWs(_ *unifi.Site) ([]*unifi.USW, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.USW, qty) + for i := 0; i < qty; i++ { var a unifi.USW + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } // GetUAPs returns all access points, an error, or nil if there are no APs. -func (m *MockUnifi) GetUAPs(site *unifi.Site) ([]*unifi.UAP, error) { +func (m *MockUnifi) GetUAPs(_ *unifi.Site) ([]*unifi.UAP, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.UAP, qty) + for i := 0; i < qty; i++ { var a unifi.UAP + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } // GetUDMs returns all dream machines, an error, or nil if there are no UDMs. -func (m *MockUnifi) GetUDMs(site *unifi.Site) ([]*unifi.UDM, error) { +func (m *MockUnifi) GetUDMs(_ *unifi.Site) ([]*unifi.UDM, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.UDM, qty) + for i := 0; i < qty; i++ { var a unifi.UDM + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } // GetUXGs returns all 10Gb gateways, an error, or nil if there are no UXGs. -func (m *MockUnifi) GetUXGs(site *unifi.Site) ([]*unifi.UXG, error) { +func (m *MockUnifi) GetUXGs(_ *unifi.Site) ([]*unifi.UXG, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.UXG, qty) + for i := 0; i < qty; i++ { var a unifi.UXG + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } // GetUSGs returns all 1Gb gateways, an error, or nil if there are no USGs. -func (m *MockUnifi) GetUSGs(site *unifi.Site) ([]*unifi.USG, error) { +func (m *MockUnifi) GetUSGs(_ *unifi.Site) ([]*unifi.USG, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.USG, qty) + for i := 0; i < qty; i++ { var a unifi.USG + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } // GetEvents returns a response full of UniFi Events for the last 1 hour from multiple sites. -func (m *MockUnifi) GetEvents(sites []*unifi.Site, hours time.Duration) ([]*unifi.Event, error) { +func (m *MockUnifi) GetEvents(_ []*unifi.Site, _ time.Duration) ([]*unifi.Event, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.Event, qty) + for i := 0; i < qty; i++ { var a unifi.Event + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } // GetSiteEvents retrieves the last 1 hour's worth of events from a single site. -func (m *MockUnifi) GetSiteEvents(site *unifi.Site, hours time.Duration) ([]*unifi.Event, error) { +func (m *MockUnifi) GetSiteEvents(_ *unifi.Site, _ time.Duration) ([]*unifi.Event, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.Event, qty) + for i := 0; i < qty; i++ { var a unifi.Event + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } // GetIDS returns Intrusion Detection Systems events for a list of Sites. // timeRange may have a length of 0, 1 or 2. The first time is Start, the second is End. // Events between start and end are returned. End defaults to time.Now(). -func (m *MockUnifi) GetIDS(sites []*unifi.Site, timeRange ...time.Time) ([]*unifi.IDS, error) { +func (m *MockUnifi) GetIDS(_ []*unifi.Site, _ ...time.Time) ([]*unifi.IDS, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.IDS, qty) + for i := 0; i < qty; i++ { var a unifi.IDS + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } // GetIDSSite retrieves the Intrusion Detection System Data for a single Site. // timeRange may have a length of 0, 1 or 2. The first time is Start, the second is End. // Events between start and end are returned. End defaults to time.Now(). -func (m *MockUnifi) GetIDSSite(site *unifi.Site, timeRange ...time.Time) ([]*unifi.IDS, error) { +func (m *MockUnifi) GetIDSSite(_ *unifi.Site, _ ...time.Time) ([]*unifi.IDS, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.IDS, qty) + for i := 0; i < qty; i++ { var a unifi.IDS + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } // GetNetworks returns a response full of network data from the UniFi Controller. -func (m *MockUnifi) GetNetworks(sites []*unifi.Site) ([]unifi.Network, error) { +func (m *MockUnifi) GetNetworks(_ []*unifi.Site) ([]unifi.Network, error) { qty := rand.Intn(5) + 1 results := make([]unifi.Network, qty) + for i := 0; i < qty; i++ { var a unifi.Network + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = a } + return results, nil } @@ -278,60 +360,80 @@ func (m *MockUnifi) GetNetworks(sites []*unifi.Site) ([]unifi.Network, error) { func (m *MockUnifi) GetSites() ([]*unifi.Site, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.Site, qty) + for i := 0; i < qty; i++ { var a unifi.Site + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } // GetSiteDPI garners dpi data for sites. -func (m *MockUnifi) GetSiteDPI(sites []*unifi.Site) ([]*unifi.DPITable, error) { +func (m *MockUnifi) GetSiteDPI(_ []*unifi.Site) ([]*unifi.DPITable, error) { qty := 1 results := make([]*unifi.DPITable, qty) + for i := 0; i < qty; i++ { var a unifi.DPITable + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } // GetRogueAPs returns RogueAPs for a list of Sites. // Use GetRogueAPsSite if you want more control. -func (m *MockUnifi) GetRogueAPs(sites []*unifi.Site) ([]*unifi.RogueAP, error) { +func (m *MockUnifi) GetRogueAPs(_ []*unifi.Site) ([]*unifi.RogueAP, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.RogueAP, qty) + for i := 0; i < qty; i++ { var a unifi.RogueAP + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } // GetRogueAPsSite returns RogueAPs for a single Site. -func (m *MockUnifi) GetRogueAPsSite(site *unifi.Site) ([]*unifi.RogueAP, error) { +func (m *MockUnifi) GetRogueAPsSite(_ *unifi.Site) ([]*unifi.RogueAP, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.RogueAP, qty) + for i := 0; i < qty; i++ { var a unifi.RogueAP + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } @@ -354,21 +456,27 @@ func (m *MockUnifi) GetServerData() (*unifi.ServerStatus, error) { if err != nil { return nil, err } + return &response, nil } // GetUsers returns a response full of clients that connected to the UDM within the provided amount of time // using the insight historical connection data set. -func (m *MockUnifi) GetUsers(sites []*unifi.Site, hours int) ([]*unifi.User, error) { +func (m *MockUnifi) GetUsers(_ []*unifi.Site, _ int) ([]*unifi.User, error) { qty := rand.Intn(5) + 1 results := make([]*unifi.User, qty) + for i := 0; i < qty; i++ { var a unifi.User + err := gofakeit.Struct(&a) + if err != nil { return results, err } + results[i] = &a } + return results, nil } diff --git a/mocks/mock_server.go b/mocks/mock_server.go index 708f6a9..d31b3a3 100644 --- a/mocks/mock_server.go +++ b/mocks/mock_server.go @@ -23,13 +23,14 @@ func NewMockHTTPTestServer() *MockHTTPTestServer { m := &MockHTTPTestServer{mocked: mocked} s := httptest.NewServer(m) m.Server = s + return m } func convertPathToRegexPattern(s string) string { tmp := strings.ReplaceAll(strings.ReplaceAll(s, "%s", "[^/]+"), "%d", "[0-9]+") + return fmt.Sprintf("(%s)?%s", unifi.APIPrefixNew, tmp) - } // compile regexp matches to paths @@ -68,32 +69,43 @@ func respondResultOrErr(w http.ResponseWriter, v any, err error, wrapWithDataAtt } else { log.Printf("[DEBUG] Answering mock response value=%+v\n", v) } + w.Header().Add("Content-Type", "application/json") w.Header().Add("Via", "unifi-mock-server") + if err != nil { e := errorResponse{ Error: err.Error(), } b, _ := json.Marshal(e) + w.WriteHeader(500) + _, _ = w.Write(b) + return } if wrapWithDataAttribute { response := dataWrapper{Data: v} b, err := json.Marshal(response) + if err != nil { e := errorResponse{ Error: err.Error(), } b, _ := json.Marshal(e) + w.WriteHeader(500) _, _ = w.Write(b) + return } + w.WriteHeader(200) + _, _ = w.Write(b) + return } @@ -104,10 +116,14 @@ func respondResultOrErr(w http.ResponseWriter, v any, err error, wrapWithDataAtt Error: err.Error(), } b, _ := json.Marshal(e) + w.WriteHeader(500) + _, _ = w.Write(b) + return } + w.WriteHeader(200) _, _ = w.Write(b) } @@ -115,103 +131,130 @@ func respondResultOrErr(w http.ResponseWriter, v any, err error, wrapWithDataAtt func (m *MockHTTPTestServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { p := strings.TrimSpace(r.URL.Path) log.Printf("[DEBUG] Received mock request path=%s\n", p) + switch { case apiRogueAP.MatchString(p): aps, err := m.mocked.GetRogueAPs(nil) respondResultOrErr(w, aps, err, true) + return case apiStatusPath.MatchString(p): s, err := m.mocked.GetServerData() respondResultOrErr(w, s, err, true) + return case apiEventPath.MatchString(p): events, err := m.mocked.GetEvents(nil, time.Hour) respondResultOrErr(w, events, err, true) + return case apiSiteList.MatchString(p): sites, err := m.mocked.GetSites() respondResultOrErr(w, sites, err, true) + return case apiSiteDPI.MatchString(p): dpi, err := m.mocked.GetSiteDPI(nil) respondResultOrErr(w, dpi, err, true) + return case apiClientDPI.MatchString(p): dpi, err := m.mocked.GetClientsDPI(nil) respondResultOrErr(w, dpi, err, true) + return case apiClientPath.MatchString(p): clients, err := m.mocked.GetClients(nil) respondResultOrErr(w, clients, err, true) + return case apiAllUserPath.MatchString(p): users, err := m.mocked.GetUsers(nil, 1) respondResultOrErr(w, users, err, true) + return case apiNetworkPath.MatchString(p): networks, err := m.mocked.GetNetworks(nil) respondResultOrErr(w, networks, err, true) + return case apiDevicePath.MatchString(p): device, err := m.mocked.GetDevices(nil) // we need to change the format response for devices. // it is an array of mixed types in a singular {"data": [...all]} devices := make([]any, 0) + for _, d := range device.UAPs { devices = append(devices, d) } + for _, d := range device.UDMs { devices = append(devices, d) } + for _, d := range device.USGs { devices = append(devices, d) } + for _, d := range device.USWs { devices = append(devices, d) } + for _, d := range device.PDUs { devices = append(devices, d) } + for _, d := range device.UXGs { devices = append(devices, d) } + respondResultOrErr(w, devices, err, true) + return case apiLoginPath.MatchString(p): err := m.mocked.Login() respondResultOrErr(w, nil, err, true) + return case apiLoginPathNew.MatchString(p): err := m.mocked.Login() respondResultOrErr(w, nil, err, true) + return case apiLogoutPath.MatchString(p): err := m.mocked.Logout() respondResultOrErr(w, nil, err, true) + return case apiEventPathIDS.MatchString(p): ids, err := m.mocked.GetIDS(nil, time.Now()) respondResultOrErr(w, ids, err, true) + return case apiEventPathAlarms.MatchString(p): alarms, err := m.mocked.GetAlarms(nil) respondResultOrErr(w, alarms, err, true) + return case apiAnomaliesPath.MatchString(p): anomalies, err := m.mocked.GetAnomalies(nil, time.Now()) respondResultOrErr(w, anomalies, err, true) + return case apiDevMgrPath.MatchString(p): // todo w.WriteHeader(501) + return case apiCommandPath.MatchString(p): // todo w.WriteHeader(501) + return default: log.Println("[DEBUG] Answering mock response err=404 not found") http.NotFoundHandler().ServeHTTP(w, r) + return } } diff --git a/networks.go b/networks.go index f9fe70f..162244a 100644 --- a/networks.go +++ b/networks.go @@ -35,6 +35,7 @@ func (u *Unifi) GetNetworks(sites []*Site) ([]Network, error) { // parseNetwork parses the raw JSON from the Unifi Controller into network structures. func (u *Unifi) parseNetwork(data json.RawMessage, siteName string) (*Network, error) { network := new(Network) + return network, u.unmarshalDevice(siteName, data, network) } @@ -50,13 +51,13 @@ type Network struct { DhcpGuardEnabled FlexBool `json:"dhcpguard_enabled"` DomainName string `json:"domain_name"` Enabled FlexBool `json:"enabled"` - ID string `json:"_id" fake:"{uuid}"` + ID string `fake:"{uuid}" json:"_id"` IPSubnet string `json:"ip_subnet"` IsNat FlexBool `json:"is_nat"` Name string `json:"name"` Networkgroup string `json:"networkgroup"` Purpose string `json:"purpose"` - SiteID string `json:"site_id" fake:"{uuid}"` + SiteID string `fake:"{uuid}" json:"site_id"` Vlan FlexInt `json:"vlan"` VlanEnabled FlexBool `json:"vlan_enabled"` } diff --git a/pdu.go b/pdu.go index 2bb28b3..0065e8f 100644 --- a/pdu.go +++ b/pdu.go @@ -5,44 +5,44 @@ import "encoding/json" // PDU is the Smart Power PDU line of products type PDU struct { site *Site - ID string `json:"_id" fake:"{uuid}"` - AdoptIP string `json:"adopt_ip" fake:"{ipv4address}"` - AdoptURL string `json:"adopt_url" fake:"{url}"` + ID string `fake:"{uuid}" json:"_id"` + AdoptIP string `fake:"{ipv4address}" json:"adopt_ip"` + AdoptURL string `fake:"{url}" json:"adopt_url"` AdoptableWhenUpgraded FlexBool `json:"adoptable_when_upgraded"` Adopted FlexBool `json:"adopted"` Anomalies FlexInt `json:"anomalies"` - AnonID string `json:"anon_id" fake:"{uuid}"` + AnonID string `fake:"{uuid}" json:"anon_id"` Architecture string `json:"architecture"` BoardRev FlexInt `json:"board_rev"` Bytes FlexInt `json:"bytes"` - CfgVersion string `json:"cfgversion" fake:"{appversion}"` + CfgVersion string `fake:"{appversion}" json:"cfgversion"` ConfigNetwork *ConfigNetwork `json:"config_network"` - ConnectRequestIP string `json:"connect_request_ip" fake:"{ipv4address}"` + ConnectRequestIP string `fake:"{ipv4address}" json:"connect_request_ip"` ConnectRequestPort FlexInt `json:"connect_request_port"` ConnectedAt FlexInt `json:"connected_at"` ConnectionNetworkName string `json:"connection_network_name"` Default FlexBool `json:"default"` - DeviceID string `json:"device_id" fake:"{uuid}"` + DeviceID string `fake:"{uuid}" json:"device_id"` DiscoveredVia string `json:"discovered_via"` - DisplayableVersion string `json:"displayable_version" fake:"{appversion}"` + DisplayableVersion string `fake:"{appversion}" json:"displayable_version"` Dot1xPortCtrlEnabled FlexBool `json:"dot1x_portctrl_enabled"` - DownlinkTable []*DownlinkTable `json:"downlink_table" fakesize:"5"` - EthernetTable []*EthernetTable `json:"ethernet_table" fakesize:"5"` + DownlinkTable []*DownlinkTable `fakesize:"5" json:"downlink_table"` + EthernetTable []*EthernetTable `fakesize:"5" json:"ethernet_table"` FlowctrlEnabled FlexBool `json:"flowctrl_enabled"` FwCaps FlexInt `json:"fw_caps"` - GatewayMac string `json:"gateway_mac" fake:"{macaddress}"` + GatewayMac string `fake:"{macaddress}" json:"gateway_mac"` GuestNumSta FlexInt `json:"guest-num_sta"` HasFan FlexBool `json:"has_fan"` HasTemperature FlexBool `json:"has_temperature"` HashID string `json:"hash_id"` HwCaps FlexInt `json:"hw_caps"` - InformIP string `json:"inform_ip" fake:"{ipv4address}"` - InformURL string `json:"inform_url" fake:"{url}"` + InformIP string `fake:"{ipv4address}" json:"inform_ip"` + InformURL string `fake:"{url}" json:"inform_url"` Internet FlexBool `json:"internet"` - IP string `json:"ip" fake:"{ipv4address}"` + IP string `fake:"{ipv4address}" json:"ip"` JumboframeEnabled FlexBool `json:"jumboframe_enabled"` - KernelVersion string `json:"kernel_version" fake:"{appversion}"` - KnownCfgVersion string `json:"known_cfgversion" fake:"{appversion}"` + KernelVersion string `fake:"{appversion}" json:"kernel_version"` + KnownCfgVersion string `fake:"{appversion}" json:"known_cfgversion"` LastSeen FlexInt `json:"last_seen"` LastUplink Uplink `json:"last_uplink"` LcmBrightness FlexInt `json:"lcm_brightness"` @@ -52,7 +52,7 @@ type PDU struct { LcmNightModeEnds string `json:"lcm_night_mode_ends"` LicenseState string `json:"license_state"` Locating FlexBool `json:"locating"` - Mac string `json:"mac" fake:"{macaddress}"` + Mac string `fake:"{macaddress}" json:"mac"` ManufacturerID FlexInt `json:"manufacturer_id"` MinIfnromIntervalSeconds FlexInt `json:"min_inform_interval_seconds"` Model string `json:"model"` @@ -65,21 +65,21 @@ type PDU struct { OutletACPowerBudget FlexInt `json:"outlet_ac_power_budget"` OutletACPowerConsumption FlexInt `json:"outlet_ac_power_consumption"` OutletEnabled FlexBool `json:"outlet_enabled"` - OutletOverrides []OutletOverride `json:"outlet_overrides" fakesize:"5"` - OutletTable []OutletTable `json:"outlet_table" fakesize:"5"` + OutletOverrides []OutletOverride `fakesize:"5" json:"outlet_overrides"` + OutletTable []OutletTable `fakesize:"5" json:"outlet_table"` Overheating FlexBool `json:"overheating"` - PortTable []Port `json:"port_table" fakesize:"5"` + PortTable []Port `fakesize:"5" json:"port_table"` PowerSource FlexInt `json:"power_source"` PowerSourceCtrlEnabled FlexBool `json:"power_source_ctrl_enabled"` PrevNonBusyState FlexInt `json:"prev_non_busy_state"` ProvisionedAt FlexInt `json:"provisioned_at"` - RequiredVersion string `json:"required_version" fake:"{appversion}"` + RequiredVersion string `fake:"{appversion}" json:"required_version"` RollUpgrade FlexBool `json:"rollupgrade"` RxBytes FlexInt `json:"rx_bytes"` Satisfaction FlexInt `json:"satisfaction"` Serial string `json:"serial"` - SetupID string `json:"setup_id" fake:"{uuid}"` - SiteID string `json:"site_id" fake:"{uuid}"` + SetupID string `fake:"{uuid}" json:"setup_id"` + SiteID string `fake:"{uuid}" json:"site_id"` SiteName string `json:"site_name"` SourceName string `json:"source_name"` StartConnectedMillis FlexInt `json:"start_connected_millis"` @@ -88,7 +88,7 @@ type PDU struct { Stat PDUStat `json:"stat"` State FlexInt `json:"state"` StpPriority FlexInt `json:"stp_priority"` - StpVersion string `json:"stp_version" fake:"{appversion}"` + StpVersion string `fake:"{appversion}" json:"stp_version"` SwitchCaps *SwitchCaps `json:"switch_caps"` SysErrorCaps FlexInt `json:"sys_error_caps"` SysStats SysStats `json:"sys_stats"` @@ -97,7 +97,7 @@ type PDU struct { TotalMaxPower FlexInt `json:"total_max_power"` TwoPhaseAdopt FlexBool `json:"two_phase_adopt"` TxBytes FlexInt `json:"tx_bytes"` - Type string `json:"type" fake:"{lexify:pdu}"` + Type string `fake:"{lexify:pdu}" json:"type"` Unsupported FlexBool `json:"unsupported"` UnsupportedReason FlexInt `json:"unsupported_reason"` Upgradeable FlexBool `json:"upgradable"` @@ -105,7 +105,7 @@ type PDU struct { UplinkDepth FlexBool `json:"uplink_depth"` Uptime FlexInt `json:"uptime"` UserNumSta FlexInt `json:"user-num_sta"` - Version string `json:"version" fake:"{appversion}"` + Version string `fake:"{appversion}" json:"version"` } // OutletOverride hold the PDU outlet override data. diff --git a/pdu_test.go b/pdu_test.go index e267151..2919a50 100644 --- a/pdu_test.go +++ b/pdu_test.go @@ -1,4 +1,4 @@ -package unifi +package unifi_test import ( _ "embed" @@ -6,6 +6,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/unpoller/unifi" ) //go:embed examples/pdu.json @@ -16,7 +17,7 @@ func TestPDUUnmarshalJSON(t *testing.T) { a := assert.New(t) powerBudgetVal := float64(1875) - p := &PDU{} + p := &unifi.PDU{} err := json.Unmarshal(pduSample, p) a.Nil(err, "must be no error unmarshaling test strings") a.Equal(powerBudgetVal, p.OutletACPowerBudget.Val, "data was not properly unmarshaled") diff --git a/site.go b/site.go index 1c73ddf..1cf644a 100644 --- a/site.go +++ b/site.go @@ -56,6 +56,7 @@ func (u *Unifi) GetSiteDPI(sites []*Site) ([]*DPITable, error) { return nil, ErrDPIDataBug } else if l == 0 { u.DebugLog("Site DPI data missing! Is DPI enabled in UniFi controller? Site %s", site.SiteName) + continue } @@ -71,9 +72,9 @@ func (u *Unifi) GetSiteDPI(sites []*Site) ([]*DPITable, error) { type Site struct { controller *Unifi SourceName string `json:"-"` - ID string `json:"_id" fake:"{uuid}"` - Name string `json:"name" fake:"{company}"` - Desc string `json:"desc" fake:"{buzzword}"` + ID string `fake:"{uuid}" json:"_id"` + Name string `fake:"{company}" json:"name"` + Desc string `fake:"{buzzword}" json:"desc"` SiteName string `json:"-"` AttrHiddenID string `json:"attr_hidden_id"` AttrNoDelete FlexBool `json:"attr_no_delete"` @@ -91,19 +92,19 @@ type Site struct { NumDisconnected FlexInt `json:"num_disconnected,omitempty"` NumPending FlexInt `json:"num_pending,omitempty"` NumGw FlexInt `json:"num_gw,omitempty"` - WanIP string `json:"wan_ip,omitempty" fake:"{ipv4address}"` - Gateways []string `json:"gateways,omitempty" fakesize:"5"` + WanIP string `fake:"{ipv4address}" json:"wan_ip,omitempty"` + Gateways []string `fakesize:"5" json:"gateways,omitempty"` Netmask string `json:"netmask,omitempty"` - Nameservers []string `json:"nameservers,omitempty" fakesize:"5"` + Nameservers []string `fakesize:"5" json:"nameservers,omitempty"` NumSta FlexInt `json:"num_sta,omitempty"` - GwMac string `json:"gw_mac,omitempty" fake:"{macaddress}"` + GwMac string `fake:"{macaddress}" json:"gw_mac,omitempty"` GwName string `json:"gw_name,omitempty"` GwSystemStats struct { CPU FlexInt `json:"cpu"` Mem FlexInt `json:"mem"` Uptime FlexInt `json:"uptime"` } `json:"gw_system-stats,omitempty"` - GwVersion string `json:"gw_version,omitempty" fake:"{appversion}"` + GwVersion string `fake:"{appversion}" json:"gw_version,omitempty"` Latency FlexInt `json:"latency,omitempty"` Uptime FlexInt `json:"uptime,omitempty"` Drops FlexInt `json:"drops,omitempty"` @@ -122,6 +123,6 @@ type Site struct { RemoteUserRxPackets FlexInt `json:"remote_user_rx_packets,omitempty"` RemoteUserTxPackets FlexInt `json:"remote_user_tx_packets,omitempty"` SiteToSiteEnabled FlexBool `json:"site_to_site_enabled,omitempty"` - } `json:"health" fakesize:"5"` + } `fakesize:"5" json:"health"` NumNewAlarms FlexInt `json:"num_new_alarms"` } diff --git a/types.go b/types.go index 0747b1f..0d15f59 100644 --- a/types.go +++ b/types.go @@ -54,10 +54,12 @@ func init() { if err != nil { return nil, err } + result := make([]int64, 0) for i := 0; i < int(l); i++ { result = append(result, gofakeit.DateRange(time.Now().Add(time.Hour-2), time.Now()).Unix()) } + return result, nil }, }) @@ -127,7 +129,7 @@ func (u *Unifi) path(path string) string { type Logger func(msg string, fmt ...interface{}) // discardLogs is the default debug logger. -func discardLogs(msg string, v ...interface{}) { +func discardLogs(_ string, _ ...interface{}) { // do nothing. } @@ -156,7 +158,7 @@ type Config struct { VerifySSL bool } -type UnifiClient interface { +type UnifiClient interface { //nolint: revive // GetAlarms returns Alarms for a list of Sites. GetAlarms(sites []*Site) ([]*Alarm, error) // GetAlarmsSite retreives the Alarms for a single Site. @@ -248,8 +250,8 @@ func (f fingerprints) Contains(s string) bool { // ServerStatus is the /status endpoint from the Unifi controller. type ServerStatus struct { Up FlexBool `json:"up"` - ServerVersion string `json:"server_version" fake:"{appversion}"` - UUID string `json:"uuid" fake:"{uuid}"` + ServerVersion string `fake:"{appversion}" json:"server_version"` + UUID string `fake:"{uuid}" json:"uuid"` } // FlexInt provides a container and unmarshalling for fields that may be @@ -328,6 +330,7 @@ func (f *FlexInt) Fake(faker *gofakeit.Faker) interface{} { Txt: strconv.FormatInt(int64(randValue), 10), } } + return FlexInt{ Val: randValue, Txt: strconv.FormatFloat(randValue, 'f', 8, 64), @@ -369,6 +372,7 @@ func (f *FlexBool) Fake(faker *gofakeit.Faker) interface{} { } v := opts[faker.Rand.Intn(2)] + return FlexBool{ Val: v, Txt: strconv.FormatBool(v), @@ -405,6 +409,7 @@ func (f *FlexTemp) UnmarshalJSON(b []byte) error { case string: f.Txt = i parts := strings.SplitN(string(b), " ", 2) + if len(parts) == 2 { // format is: $val(int or float) $unit(C or F) f.Val, _ = strconv.ParseFloat(parts[0], 64) @@ -474,6 +479,7 @@ func (f *FlexTemp) Fake(faker *gofakeit.Faker) interface{} { Txt: strconv.FormatInt(int64(randValue), 10) + " C", } } + return FlexTemp{ Val: randValue, Txt: strconv.FormatFloat(randValue, 'f', 8, 64) + " C", @@ -485,19 +491,19 @@ type DownlinkTable struct { PortIdx FlexInt `json:"port_idx"` Speed FlexInt `json:"speed"` FullDuplex FlexBool `json:"full_duplex"` - Mac string `json:"mac" fake:"{macaddress}"` + Mac string `fake:"{macaddress}" json:"mac"` } // ConfigNetwork comes from gateways. type ConfigNetwork struct { - Type string `json:"type" fake:"{randomstring:[wan,lan,vlan]}"` - IP string `json:"ip" fake:"{ipv4address}"` + Type string `fake:"{randomstring:[wan,lan,vlan]}" json:"type"` + IP string `fake:"{ipv4address}" json:"ip"` } type EthernetTable struct { - Mac string `json:"mac" fake:"{macaddress}"` + Mac string `fake:"{macaddress}" json:"mac"` NumPort FlexInt `json:"num_port"` - Name string `json:"name" fake:"{animal}"` + Name string `fake:"{animal}" json:"name"` } // Port is a physical connection on a USW or Gateway. @@ -506,23 +512,23 @@ type Port struct { AggregatedBy FlexBool `json:"aggregated_by"` Autoneg FlexBool `json:"autoneg,omitempty"` BytesR FlexInt `json:"bytes-r"` - DNS []string `json:"dns,omitempty" fakesize:"5"` + DNS []string `fakesize:"5" json:"dns,omitempty"` Dot1XMode string `json:"dot1x_mode"` Dot1XStatus string `json:"dot1x_status"` Enable FlexBool `json:"enable"` FlowctrlRx FlexBool `json:"flowctrl_rx"` FlowctrlTx FlexBool `json:"flowctrl_tx"` FullDuplex FlexBool `json:"full_duplex"` - IP string `json:"ip,omitempty" fake:"{ipv4address}"` - Ifname string `json:"ifname,omitempty" fake:"{randomstring:[wlan0,wlan1,lan0,lan1,vlan1,vlan0,vlan2]}"` + IP string `fake:"{ipv4address}" json:"ip,omitempty"` + Ifname string `fake:"{randomstring:[wlan0,wlan1,lan0,lan1,vlan1,vlan0,vlan2]}" json:"ifname,omitempty"` IsUplink FlexBool `json:"is_uplink"` - Mac string `json:"mac,omitempty" fake:"{macaddress}"` - MacTable []MacTable `json:"mac_table,omitempty" fakesize:"5"` + Mac string `fake:"{macaddress}" json:"mac,omitempty"` + MacTable []MacTable `fakesize:"5" json:"mac_table,omitempty"` Jumbo FlexBool `json:"jumbo,omitempty"` Masked FlexBool `json:"masked"` Media string `json:"media"` - Name string `json:"name" fake:"{animal}"` - NetworkName string `json:"network_name,omitempty" fake:"{animal}"` + Name string `fake:"{animal}" json:"name"` + NetworkName string `fake:"{animal}" json:"network_name,omitempty"` Netmask string `json:"netmask,omitempty"` NumPort FlexInt `json:"num_port,omitempty"` OpMode string `json:"op_mode"` diff --git a/uap.go b/uap.go index 8141bb7..138311b 100644 --- a/uap.go +++ b/uap.go @@ -16,30 +16,30 @@ type UAP struct { AntennaTable []struct { Default FlexBool `json:"default"` ID FlexInt `json:"id"` - Name string `json:"name" fake:"{animal}"` + Name string `fake:"{animal}" json:"name"` Wifi0Gain FlexInt `json:"wifi0_gain"` Wifi1Gain FlexInt `json:"wifi1_gain"` - } `json:"antenna_table" fakesize:"5"` + } `fakesize:"5" json:"antenna_table"` Architecture string `json:"architecture"` BandsteeringMode string `json:"bandsteering_mode,omitempty"` BoardRev int `json:"board_rev"` Bytes FlexInt `json:"bytes"` BytesD FlexInt `json:"bytes-d"` BytesR FlexInt `json:"bytes-r"` - Cfgversion string `json:"cfgversion" fake:"{appversion}"` + Cfgversion string `fake:"{appversion}" json:"cfgversion"` ConfigNetwork *ConfigNetwork `json:"config_network"` - ConnectRequestIP string `json:"connect_request_ip" fake:"{ipv4address}"` + ConnectRequestIP string `fake:"{ipv4address}" json:"connect_request_ip"` ConnectRequestPort string `json:"connect_request_port"` ConnectedAt FlexInt `json:"connected_at"` CountryCode FlexInt `json:"country_code"` - CountrycodeTable []int `json:"countrycode_table" fakesize:"5"` - DeviceID string `json:"device_id" fake:"{uuid}"` + CountrycodeTable []int `fakesize:"5" json:"countrycode_table"` + DeviceID string `fake:"{uuid}" json:"device_id"` Dot1XPortctrlEnabled FlexBool `json:"dot1x_portctrl_enabled"` - DownlinkTable []*DownlinkTable `json:"downlink_table,omitempty" fakesize:"5"` - EthernetTable []*EthernetTable `json:"ethernet_table" fakesize:"5"` + DownlinkTable []*DownlinkTable `fakesize:"5" json:"downlink_table,omitempty"` + EthernetTable []*EthernetTable `fakesize:"5" json:"ethernet_table"` FixedAPAvailable FlexBool `json:"fixed_ap_available"` FwCaps int `json:"fw_caps"` - GatewayMac string `json:"gateway_mac" fake:"{macaddress}"` + GatewayMac string `fake:"{macaddress}" json:"gateway_mac"` GuestNumSta FlexInt `json:"guest-num_sta"` GuestToken string `json:"guest_token"` GuestWlanNumSta FlexInt `json:"guest-wlan-num_sta"` @@ -48,18 +48,18 @@ type UAP struct { HasSpeaker FlexBool `json:"has_speaker"` HasTemperature FlexBool `json:"has_temperature"` HwCaps int `json:"hw_caps"` - ID string `json:"_id" fake:"{uuid}"` - IP string `json:"ip" fake:"{ipv4address}"` - InformIP string `json:"inform_ip" fake:"{ipv4address}"` - InformURL string `json:"inform_url" fake:"{url}"` + ID string `fake:"{uuid}" json:"_id"` + IP string `fake:"{ipv4address}" json:"ip"` + InformIP string `fake:"{ipv4address}" json:"inform_ip"` + InformURL string `fake:"{url}" json:"inform_url"` Internet FlexBool `json:"internet"` Isolated FlexBool `json:"isolated"` - KernelVersion string `json:"kernel_version" fake:"{appversion}"` - KnownCfgversion string `json:"known_cfgversion" fake:"{appversion}"` + KernelVersion string `fake:"{appversion}" json:"kernel_version"` + KnownCfgversion string `fake:"{appversion}" json:"known_cfgversion"` LastSeen FlexInt `json:"last_seen"` LastUplink struct { - UplinkMac string `json:"uplink_mac" fake:"{macaddress}"` - UplinkRemotePort int `json:"uplink_remote_port" fake:"{port}"` + UplinkMac string `fake:"{macaddress}" json:"uplink_mac"` + UplinkRemotePort int `fake:"{port}" json:"uplink_remote_port"` } `json:"last_uplink"` LcmBrightnessOverride FlexBool `json:"lcm_brightness_override"` LcmTimeoutOverride FlexBool `json:"lcm_idle_timeout_override"` @@ -81,7 +81,7 @@ type UAP struct { LteHardLimit FlexInt `json:"lte_hard_limit"` LteICCID string `json:"lte_iccid"` LteIMEI string `json:"lte_imei"` - LteIP string `json:"lte_ip" fake:"{ipv4address}"` + LteIP string `fake:"{ipv4address}" json:"lte_ip"` LteMode string `json:"lte_mode"` LteNetworkOperator string `json:"lte_networkoperator"` LtePdpType string `json:"lte_pdptype"` @@ -95,13 +95,13 @@ type UAP struct { LteRxChannel FlexInt `json:"lte_rx_chan"` LteSignal string `json:"lte_signal"` LteSoftLimit FlexInt `json:"lte_soft_limit"` - LteSsoUserUuid string `json:"lte_sso_user_uuid"` + LteSsoUserUuid string `json:"lte_sso_user_uuid"` //nolint:revive LteState FlexBool `json:"lte_state"` - LteSubscriptionApiUnreachable FlexBool `json:"lte_subscription_api_unreachable"` + LteSubscriptionApiUnreachable FlexBool `json:"lte_subscription_api_unreachable"` //nolint:revive LteSubscriptionCheckRequired FlexBool `json:"lte_subscription_check_required"` LteSubscriptionStatus FlexBool `json:"lte_subscription_status"` LteTxChannel FlexInt `json:"lte_tx_chan"` - Mac string `json:"mac" fake:"{macaddress}"` + Mac string `fake:"{macaddress}" json:"mac"` ManufacturerID FlexInt `json:"manufacturer_id"` MeshStaVapEnabled FlexBool `json:"mesh_sta_vap_enabled"` Meshv3PeerMac string `json:"meshv3_peer_mac"` @@ -112,11 +112,11 @@ type UAP struct { Name string `json:"name"` NumSta FlexInt `json:"num_sta"` OutdoorModeOverride string `json:"outdoor_mode_override"` - PortTable []Port `json:"port_table" fakesize:"5"` + PortTable []Port `fakesize:"5" json:"port_table"` ProvisionedAt FlexInt `json:"provisioned_at"` RadioTable RadioTable `json:"radio_table"` RadioTableStats RadioTableStats `json:"radio_table_stats"` - RequiredVersion string `json:"required_version" fake:"{appversion}"` + RequiredVersion string `fake:"{appversion}" json:"required_version"` Rollupgrade FlexBool `json:"rollupgrade"` RxBytes FlexInt `json:"rx_bytes"` RxBytesD FlexInt `json:"rx_bytes-d"` @@ -125,7 +125,7 @@ type UAP struct { ScanRadioTable []interface{} `json:"scan_radio_table"` Scanning FlexBool `json:"scanning"` Serial string `json:"serial"` - SiteID string `json:"site_id" fake:"{uuid}"` + SiteID string `fake:"{uuid}" json:"site_id"` SiteName string `json:"-"` SourceName string `json:"-"` SpectrumScanning FlexBool `json:"spectrum_scanning"` @@ -144,7 +144,7 @@ type UAP struct { TwoPhaseAdopt FlexBool `json:"two_phase_adopt,omitempty"` TxBytes FlexInt `json:"tx_bytes"` TxBytesD FlexInt `json:"tx_bytes-d"` - Type string `json:"type" fake:"{lexify:uap}"` + Type string `fake:"{lexify:uap}" json:"type"` UUptime FlexInt `json:"_uptime"` Unsupported FlexBool `json:"unsupported"` UnsupportedReason FlexInt `json:"unsupported_reason"` @@ -152,12 +152,12 @@ type UAP struct { UpgradeState FlexInt `json:"upgrade_state"` Uplink struct { FullDuplex FlexBool `json:"full_duplex"` - IP string `json:"ip" fake:"{ipv4address}"` - Mac string `json:"mac" fake:"{macaddress}"` + IP string `fake:"{ipv4address}" json:"ip"` + Mac string `fake:"{macaddress}" json:"mac"` MaxVlan int `json:"max_vlan"` Name string `json:"name"` Netmask string `json:"netmask"` - NumPort int `json:"num_port" fake:"{port}"` + NumPort int `fake:"{port}" json:"num_port"` RxBytes FlexInt `json:"rx_bytes"` RxDropped FlexInt `json:"rx_dropped"` RxErrors FlexInt `json:"rx_errors"` @@ -173,15 +173,15 @@ type UAP struct { Type string `json:"type"` TxBytesR FlexInt `json:"tx_bytes-r"` RxBytesR FlexInt `json:"rx_bytes-r"` - UplinkMac string `json:"uplink_mac" fake:"{macaddress}"` - UplinkRemotePort int `json:"uplink_remote_port" fake:"{port}"` + UplinkMac string `fake:"{macaddress}" json:"uplink_mac"` + UplinkRemotePort int `fake:"{port}" json:"uplink_remote_port"` } `json:"uplink"` UplinkTable []interface{} `json:"uplink_table"` Uptime FlexInt `json:"uptime"` UserNumSta FlexInt `json:"user-num_sta"` UserWlanNumSta FlexInt `json:"user-wlan-num_sta"` VapTable VapTable `json:"vap_table"` - Version string `json:"version" fake:"{appversion}"` + Version string `fake:"{appversion}" json:"version"` VwireEnabled FlexBool `json:"vwireEnabled"` VwireTable []interface{} `json:"vwire_table"` VwireVapTable []interface{} `json:"vwire_vap_table"` @@ -198,7 +198,7 @@ type UAPStat struct { // Ap is a subtype of UAPStat to make unmarshalling of different controller versions possible. type Ap struct { - SiteID string `json:"site_id" fake:"{uuid}"` + SiteID string `fake:"{uuid}" json:"site_id"` O string `json:"o"` Oid string `json:"oid"` Ap string `json:"ap"` @@ -440,7 +440,7 @@ type RadioTable []struct { MinRssi FlexInt `json:"min_rssi,omitempty"` MinRssiEnabled FlexBool `json:"min_rssi_enabled"` MinTxpower FlexInt `json:"min_txpower"` - Name string `json:"name" fake:"{animal}"` + Name string `fake:"{animal}" json:"name"` Nss FlexInt `json:"nss"` Radio string `json:"radio"` RadioCaps FlexInt `json:"radio_caps"` @@ -448,12 +448,12 @@ type RadioTable []struct { TxPower FlexInt `json:"tx_power"` TxPowerMode string `json:"tx_power_mode"` VwireEnabled FlexBool `json:"vwire_enabled"` - WlangroupID string `json:"wlangroup_id" fake:"{uuid}"` + WlangroupID string `fake:"{uuid}" json:"wlangroup_id"` } // RadioTableStats is part of the data shared between UAP and UDM. type RadioTableStats []struct { - Name string `json:"name" fake:"{animal}"` + Name string `fake:"{animal}" json:"name"` Channel FlexInt `json:"channel"` Radio string `json:"radio"` AstTxto interface{} `json:"ast_txto"` @@ -553,20 +553,20 @@ type VapTable []struct { Total FlexInt `json:"total"` TotalCount FlexInt `json:"total_count"` } `json:"wifi_tx_latency_mov"` - ApMac string `json:"ap_mac" fake:"{macaddress}"` + ApMac string `fake:"{macaddress}" json:"ap_mac"` AvgClientSignal FlexInt `json:"avg_client_signal"` - Bssid string `json:"bssid" fake:"{macaddress}"` + Bssid string `fake:"{macaddress}" json:"bssid"` Ccq int `json:"ccq"` Channel FlexInt `json:"channel"` DNSAvgLatency FlexInt `json:"dns_avg_latency"` - Essid string `json:"essid" fake:"{macaddress}"` + Essid string `fake:"{macaddress}" json:"essid"` Extchannel int `json:"extchannel"` - ID string `json:"id" fake:"{uuid}"` + ID string `fake:"{uuid}" json:"id"` IsGuest FlexBool `json:"is_guest"` IsWep FlexBool `json:"is_wep"` MacFilterRejections int `json:"mac_filter_rejections"` MapID interface{} `json:"map_id"` - Name string `json:"name" fake:"{animal}"` + Name string `fake:"{animal}" json:"name"` NumSatisfactionSta FlexInt `json:"num_satisfaction_sta"` NumSta int `json:"num_sta"` Radio string `json:"radio"` @@ -580,7 +580,7 @@ type VapTable []struct { RxPackets FlexInt `json:"rx_packets"` Satisfaction FlexInt `json:"satisfaction"` SatisfactionNow FlexInt `json:"satisfaction_now"` - SiteID string `json:"site_id" fake:"{uuid}"` + SiteID string `fake:"{uuid}" json:"site_id"` State string `json:"state"` T string `json:"t"` TxBytes FlexInt `json:"tx_bytes"` @@ -605,16 +605,16 @@ type VapTable []struct { type RogueAP struct { SourceName string `json:"-"` SiteName string `json:"-"` - ID string `json:"_id" fake:"{uuid}"` - ApMac string `json:"ap_mac" fake:"{macaddress}"` - Bssid string `json:"bssid" fake:"{macaddress}"` - SiteID string `json:"site_id" fake:"{uuid}"` + ID string `fake:"{uuid}" json:"_id"` + ApMac string `fake:"{macaddress}" json:"ap_mac"` + Bssid string `fake:"{macaddress}" json:"bssid"` + SiteID string `fake:"{uuid}" json:"site_id"` Age FlexInt `json:"age"` Band string `json:"band"` Bw FlexInt `json:"bw"` CenterFreq FlexInt `json:"center_freq"` Channel int `json:"channel"` - Essid string `json:"essid" fake:"{macaddress}"` + Essid string `fake:"{macaddress}" json:"essid"` Freq FlexInt `json:"freq"` IsAdhoc FlexBool `json:"is_adhoc"` IsRogue FlexBool `json:"is_rogue"` diff --git a/udm.go b/udm.go index 8692908..a660cf9 100644 --- a/udm.go +++ b/udm.go @@ -5,12 +5,12 @@ package unifi type UDM struct { site *Site AFTEnabled FlexBool `json:"atf_enabled"` - AdoptIP string `json:"adopt_ip" fake:"{ipv4address}"` + AdoptIP string `fake:"{ipv4address}" json:"adopt_ip"` AdoptManual FlexBool `json:"adopt_manual"` AdoptState FlexInt `json:"adopt_state"` AdoptStatus FlexInt `json:"adopt_status"` AdoptTries FlexInt `json:"adopt_tries"` - AdoptURL string `json:"adopt_url" fake:"{url}"` + AdoptURL string `fake:"{url}" json:"adopt_url"` AdoptableWhenUpgraded FlexBool `json:"adoptable_when_upgraded"` Adopted FlexBool `json:"adopted"` AdoptionCompleted FlexBool `json:"adoption_completed"` @@ -20,24 +20,24 @@ type UDM struct { Bytes FlexInt `json:"bytes"` BytesD FlexInt `json:"bytes-d"` BytesR FlexInt `json:"bytes-r"` - Cfgversion string `json:"cfgversion" fake:"{appversion}"` + Cfgversion string `fake:"{appversion}" json:"cfgversion"` ConfigNetwork *ConfigNetwork `json:"config_network"` - ConnectRequestIP string `json:"connect_request_ip" fake:"{ipv4address}"` + ConnectRequestIP string `fake:"{ipv4address}" json:"connect_request_ip"` ConnectRequestPort string `json:"connect_request_port"` ConnectedAt FlexInt `json:"connected_at"` ConnectionNetworkName string `json:"connection_network_name"` Default FlexBool `json:"default"` DeviceDomain string `json:"device_domain"` - DeviceID string `json:"device_id" fake:"{uuid}"` + DeviceID string `fake:"{uuid}" json:"device_id"` DiscoveredVia string `json:"discovered_via"` - DisplayableVersion string `json:"displayable_version" fake:"{appversion}"` + DisplayableVersion string `fake:"{appversion}" json:"displayable_version"` Dot1XPortctrlEnabled FlexBool `json:"dot1x_portctrl_enabled"` - DownlinkTable []*DownlinkTable `json:"downlink_table" fakesize:"5"` - EthernetOverrides []*EthernetOverrides `json:"ethernet_overrides" fakesize:"5"` - EthernetTable []*EthernetTable `json:"ethernet_table" fakesize:"5"` + DownlinkTable []*DownlinkTable `fakesize:"5" json:"downlink_table"` + EthernetOverrides []*EthernetOverrides `fakesize:"5" json:"ethernet_overrides"` + EthernetTable []*EthernetTable `fakesize:"5" json:"ethernet_table"` FlowctrlEnabled FlexBool `json:"flowctrl_enabled"` FwCaps FlexInt `json:"fw_caps"` - GeoInfo map[string]GeoInfo `json:"geo_info" fakesize:"5"` + GeoInfo map[string]GeoInfo `fakesize:"5" json:"geo_info"` GuestKicks FlexInt `json:"guest_kicks"` GuestLanNumSta FlexInt `json:"guest-lan-num_sta"` // USW GuestNumSta FlexInt `json:"guest-num_sta"` // USG @@ -48,20 +48,20 @@ type UDM struct { HasSpeaker FlexBool `json:"has_speaker"` HasTemperature FlexBool `json:"has_temperature"` HwCaps FlexInt `json:"hw_caps"` - ID string `json:"_id" fake:"{uuid}"` - IP string `json:"ip" fake:"{ipv4address}"` - InformIP string `json:"inform_ip" fake:"{ipv4address}"` - InformURL string `json:"inform_url" fake:"{url}"` + ID string `fake:"{uuid}" json:"_id"` + IP string `fake:"{ipv4address}" json:"ip"` + InformIP string `fake:"{ipv4address}" json:"inform_ip"` + InformURL string `fake:"{url}" json:"inform_url"` Internet FlexBool `json:"internet"` IsAccessPoint FlexBool `json:"is_access_point"` JumboframeEnabled FlexBool `json:"jumboframe_enabled"` - KernelVersion string `json:"kernel_version" fake:"{appversion}"` - KnownCfgversion string `json:"known_cfgversion" fake:"{appversion}"` - LanIP string `json:"lan_ip" fake:"{ipv4address}"` + KernelVersion string `fake:"{appversion}" json:"kernel_version"` + KnownCfgversion string `fake:"{appversion}" json:"known_cfgversion"` + LanIP string `fake:"{ipv4address}" json:"lan_ip"` LanNumSta FlexInt `json:"lan-num_sta"` // USW LastLteFailoverTransitionTimestamp FlexInt `json:"last_lte_failover_transition_timestamp"` LastSeen FlexInt `json:"last_seen"` - LastWlanIP string `json:"last_wan_ip" fake:"{ipv4address}"` + LastWlanIP string `fake:"{ipv4address}" json:"last_wan_ip"` LcmBrightness FlexInt `json:"lcm_brightness"` LcmNightModeBegins string `json:"lcm_night_mode_begins"` LcmNightModeEnabled FlexBool `json:"lcm_night_mode_enabled"` @@ -70,14 +70,14 @@ type UDM struct { LcmTrackerSeed string `json:"lcm_tracker_seed"` LicenseState string `json:"license_state"` Locating FlexBool `json:"locating"` - Mac string `json:"mac" fake:"{macaddress}"` + Mac string `fake:"{macaddress}" json:"mac"` ManufacturerID FlexInt `json:"manufacturer_id"` MinInformIntervalSeconds FlexInt `json:"min_inform_interval_seconds"` Model string `json:"model"` ModelInEOL FlexBool `json:"model_in_eol"` ModelInLTS FlexBool `json:"model_in_lts"` ModelIncompatible FlexBool `json:"model_incompatible"` - Name string `json:"name" fake:"{animal}"` + Name string `fake:"{animal}" json:"name"` NetworkTable NetworkTable `json:"network_table"` NextInterval FlexInt `json:"next_interval"` NumDesktop FlexInt `json:"num_desktop"` // USG @@ -88,13 +88,13 @@ type UDM struct { PortOverrides []struct { PortIdx FlexInt `json:"port_idx"` PortconfID string `json:"portconf_id"` - } `json:"port_overrides" fakesize:"5"` - PortTable []Port `json:"port_table" fakesize:"5"` + } `fakesize:"5" json:"port_overrides"` + PortTable []Port `fakesize:"5" json:"port_table"` PowerSourceCtrlEnabled FlexBool `json:"power_source_ctrl_enabled"` ProvisionedAt FlexInt `json:"provisioned_at"` RadioTable *RadioTable `json:"radio_table,omitempty"` RadioTableStats *RadioTableStats `json:"radio_table_stats,omitempty"` - RequiredVersion string `json:"required_version" fake:"{appversion}"` + RequiredVersion string `fake:"{appversion}" json:"required_version"` RollUpgrade FlexBool `json:"rollupgrade"` RulesetInterfaces interface{} `json:"ruleset_interfaces"` /* struct { @@ -114,7 +114,7 @@ type UDM struct { Serial string `json:"serial"` SetupProvisionCompleted FlexBool `json:"setup_provision_completed"` SetupProvisionTracking FlexBool `json:"setup_provision_tracking"` - SiteID string `json:"site_id" fake:"{uuid}"` + SiteID string `fake:"{uuid}" json:"site_id"` SiteName string `json:"-"` SourceName string `json:"-"` SpeedtestStatus SpeedtestStatus `json:"speedtest-status"` @@ -124,9 +124,9 @@ type UDM struct { StartupTimestamp FlexInt `json:"startup_timestamp"` Stat UDMStat `json:"stat"` State FlexInt `json:"state"` - Storage []*Storage `json:"storage" fakesize:"5"` + Storage []*Storage `fakesize:"5" json:"storage"` StpPriority FlexInt `json:"stp_priority"` - StpVersion string `json:"stp_version" fake:"{appversion}"` + StpVersion string `fake:"{appversion}" json:"stp_version"` SwitchCaps struct { MaxMirrorSessions FlexInt `json:"max_mirror_sessions"` MaxAggregateSessions FlexInt `json:"max_aggregate_sessions"` @@ -135,22 +135,22 @@ type UDM struct { SyslogKey string `json:"syslog_key"` SystemStats SystemStats `json:"system-stats"` TeleportVersion FlexInt `json:"teleport_version"` - Temperatures []Temperature `json:"temperatures,omitempty" fakesize:"5"` + Temperatures []Temperature `fakesize:"5" json:"temperatures,omitempty"` TwoPhaseAdopt FlexBool `json:"two_phase_adopt"` TxBytes FlexInt `json:"tx_bytes"` TxBytesD FlexInt `json:"tx_bytes-d"` - Type string `json:"type" fake:"{lexify:udmp}"` + Type string `fake:"{lexify:udmp}" json:"type"` UdapiCaps FlexInt `json:"udapi_caps"` UnifiCare struct { ActivationDismissed FlexBool `json:"activation_dismissed"` ActivationEnd FlexInt `json:"activation_end"` - ActivationUrl string `json:"activation_url" fake:"{url}"` + ActivationUrl string `fake:"{url}" json:"activation_url"` //nolint:revive CoverageEnd FlexInt `json:"coverage_end"` CoverageStart FlexInt `json:"coverage_start"` Registration FlexInt `json:"registration"` - RmaUrl string `json:"rma_url" fake:"{url}"` + RmaUrl string `fake:"{url}" json:"rma_url"` //nolint:revive State string `json:"state"` - TrackingUrl string `json:"tracking_url" fake:"{url}"` + TrackingUrl string `fake:"{url}" json:"tracking_url"` //nolint:revive } `json:"unifi_care"` Unsupported FlexBool `json:"unsupported"` UnsupportedReason FlexInt `json:"unsupported_reason"` @@ -163,7 +163,7 @@ type UDM struct { UserWlanNumSta FlexInt `json:"user-wlan-num_sta"` // UAP UsgCaps FlexInt `json:"usg_caps"` VapTable *VapTable `json:"vap_table"` - Version string `json:"version" fake:"{appversion}"` + Version string `fake:"{appversion}" json:"version"` VwireTable []interface{} `json:"vwire_table"` Wan1 Wan `json:"wan1"` Wan2 Wan `json:"wan2"` @@ -182,7 +182,7 @@ type EthernetOverrides struct { // NetworkTable is the list of networks on a gateway. // Not all gateways have all features. type NetworkTable []struct { - ID string `json:"_id" fake:"{uuid}"` + ID string `fake:"{uuid}" json:"_id"` ActiveDhcpLeaseCount FlexInt `json:"active_dhcp_lease_count"` AttrHiddenID string `json:"attr_hidden_id"` AttrNoDelete FlexBool `json:"attr_no_delete"` @@ -204,7 +204,7 @@ type NetworkTable []struct { DPIStatsTable *DPITable `json:"dpistats_table"` Enabled FlexBool `json:"enabled"` GatewayInterfaceName string `json:"gateway_interface_name"` - IP string `json:"ip" fake:"{ipv4address}"` + IP string `fake:"{ipv4address}" json:"ip"` IPSubnet string `json:"ip_subnet"` Ipv6InterfaceType string `json:"ipv6_interface_type"` Ipv6PdStart string `json:"ipv6_pd_start"` @@ -213,14 +213,14 @@ type NetworkTable []struct { IsGuest FlexBool `json:"is_guest"` IsNat FlexBool `json:"is_nat"` LteLanEnabled FlexBool `json:"lte_lan_enabled"` - Mac string `json:"mac" fake:"{macaddress}"` - Name string `json:"name" fake:"{animal}"` + Mac string `fake:"{macaddress}" json:"mac"` + Name string `fake:"{animal}" json:"name"` Networkgroup string `json:"networkgroup"` NumSta FlexInt `json:"num_sta"` Purpose string `json:"purpose"` RxBytes FlexInt `json:"rx_bytes"` RxPackets FlexInt `json:"rx_packets"` - SiteID string `json:"site_id" fake:"{uuid}"` + SiteID string `fake:"{uuid}" json:"site_id"` TxBytes FlexInt `json:"tx_bytes"` TxPackets FlexInt `json:"tx_packets"` Up FlexBool `json:"up"` @@ -230,14 +230,14 @@ type NetworkTable []struct { // Storage is hard drive into for a device with storage. type Storage struct { MountPoint string `json:"mount_point"` - Name string `json:"name" fake:"{animal}"` + Name string `fake:"{animal}" json:"name"` Size FlexInt `json:"size"` Type string `json:"type"` Used FlexInt `json:"used"` } type Temperature struct { - Name string `json:"name" fake:"{animal}"` + Name string `fake:"{animal}" json:"name"` Type string `json:"type"` Value float64 `json:"value"` } diff --git a/unifi.go b/unifi.go index 0100fbf..c37ac2e 100644 --- a/unifi.go +++ b/unifi.go @@ -99,7 +99,7 @@ func newUnifi(config *Config, jar http.CookieJar) *Unifi { return u } -func (u *Unifi) verifyPeerCertificate(certs [][]byte, chains [][]*x509.Certificate) error { +func (u *Unifi) verifyPeerCertificate(certs [][]byte, _ [][]*x509.Certificate) error { if len(u.fingerprints) == 0 { return nil } @@ -145,6 +145,7 @@ func (u *Unifi) Login() error { func (u *Unifi) Logout() error { // a post is needed for logout _, err := u.PostJSON(APILogoutPath) + return err } diff --git a/users.go b/users.go index 81145b8..aa033dd 100644 --- a/users.go +++ b/users.go @@ -45,9 +45,9 @@ func (u *Unifi) GetUsers(sites []*Site, hours int) ([]*User, error) { type User struct { SourceName string `json:"-"` SiteName string `json:"-"` - ID string `json:"_id" fake:"{uuid}"` - Mac string `json:"mac" fake:"{macaddress}"` - SiteID string `json:"site_id" fake:"{uuid}"` + ID string `fake:"{uuid}" json:"_id"` + Mac string `fake:"{macaddress}" json:"mac"` + SiteID string `fake:"{uuid}" json:"site_id"` Oui string `json:"oui,omitempty"` IsGuest bool `json:"is_guest"` FirstSeen FlexInt `json:"first_seen,omitempty"` @@ -62,12 +62,12 @@ type User struct { WifiTxAttempts FlexInt `json:"wifi_tx_attempts,omitempty"` TxRetries FlexInt `json:"tx_retries,omitempty"` UsergroupID string `json:"usergroup_id,omitempty"` - Name string `json:"name,omitempty" fake:"{animal}"` - Note string `json:"note,omitempty" fake:"{buzzword}"` + Name string `fake:"{animal}" json:"name,omitempty"` + Note string `fake:"{buzzword}" json:"note,omitempty"` Noted FlexBool `json:"noted,omitempty"` Blocked FlexBool `json:"blocked,omitempty"` DevIDOverride FlexInt `json:"dev_id_override,omitempty"` FingerprintOverride FlexBool `json:"fingerprint_override,omitempty"` - UseFixedIp FlexBool `json:"use_fixedip,omitempty"` - FixedIp string `json:"fixed_ip,omitempty" fake:"{ipv4address}"` + UseFixedIp FlexBool `json:"use_fixedip,omitempty"` //nolint:revive + FixedIp string `fake:"{ipv4address}" json:"fixed_ip,omitempty"` //nolint:revive } diff --git a/usg.go b/usg.go index df28aeb..d381f6c 100644 --- a/usg.go +++ b/usg.go @@ -9,53 +9,53 @@ import ( type USG struct { site *Site SourceName string `json:"-"` - ID string `json:"_id" fake:"{uuid}"` + ID string `fake:"{uuid}" json:"_id"` Adopted FlexBool `json:"adopted"` - Cfgversion string `json:"cfgversion" fake:"{appversion}"` + Cfgversion string `fake:"{appversion}" json:"cfgversion"` ConfigNetwork *ConfigNetwork `json:"config_network"` - EthernetTable []*EthernetTable `json:"ethernet_table" fakesize:"5"` + EthernetTable []*EthernetTable `fakesize:"5" json:"ethernet_table"` FwCaps FlexInt `json:"fw_caps"` - InformIP string `json:"inform_ip" fake:"{ipv4address}"` - InformURL string `json:"inform_url" fake:"{url}"` - IP string `json:"ip" fake:"{ipv4address}"` + InformIP string `fake:"{ipv4address}" json:"inform_ip"` + InformURL string `fake:"{url}" json:"inform_url"` + IP string `fake:"{ipv4address}" json:"ip"` LedOverride string `json:"led_override"` LicenseState string `json:"license_state"` - Mac string `json:"mac" fake:"{macaddress}"` + Mac string `fake:"{macaddress}" json:"mac"` Model string `json:"model"` - Name string `json:"name" fake:"{animal}"` + Name string `fake:"{animal}" json:"name"` OutdoorModeOverride string `json:"outdoor_mode_override"` Serial string `json:"serial"` - SiteID string `json:"site_id" fake:"{uuid}"` + SiteID string `fake:"{uuid}" json:"site_id"` SiteName string `json:"-"` - Type string `json:"type" fake:"{lexify:usg}"` + Type string `fake:"{lexify:usg}" json:"type"` UsgCaps FlexInt `json:"usg_caps"` - Version string `json:"version" fake:"{appversion}"` - RequiredVersion string `json:"required_version" fake:"{appversion}"` - EthernetOverrides []*EthernetOverrides `json:"ethernet_overrides" fakesize:"5"` + Version string `fake:"{appversion}" json:"version"` + RequiredVersion string `fake:"{appversion}" json:"required_version"` + EthernetOverrides []*EthernetOverrides `fakesize:"5" json:"ethernet_overrides"` HwCaps FlexInt `json:"hw_caps"` BoardRev FlexInt `json:"board_rev"` Unsupported FlexBool `json:"unsupported"` UnsupportedReason FlexInt `json:"unsupported_reason"` - DeviceID string `json:"device_id" fake:"{uuid}"` + DeviceID string `fake:"{uuid}" json:"device_id"` State FlexInt `json:"state"` LastSeen FlexInt `json:"last_seen"` Upgradable FlexBool `json:"upgradable"` AdoptableWhenUpgraded FlexBool `json:"adoptable_when_upgraded"` Rollupgrade FlexBool `json:"rollupgrade"` - KnownCfgversion string `json:"known_cfgversion" fake:"{appversion}"` + KnownCfgversion string `fake:"{appversion}" json:"known_cfgversion"` Uptime FlexInt `json:"uptime"` Locating FlexBool `json:"locating"` - ConnectRequestIP string `json:"connect_request_ip" fake:"{ipv4address}"` + ConnectRequestIP string `fake:"{ipv4address}" json:"connect_request_ip"` ConnectRequestPort string `json:"connect_request_port"` SysStats SysStats `json:"sys_stats"` - Temperatures []Temperature `json:"temperatures,omitempty" fakesize:"5"` + Temperatures []Temperature `fakesize:"5" json:"temperatures,omitempty"` SystemStats SystemStats `json:"system-stats"` GuestToken string `json:"guest_token"` SpeedtestStatus SpeedtestStatus `json:"speedtest-status"` SpeedtestStatusSaved FlexBool `json:"speedtest-status-saved"` Wan1 Wan `json:"wan1"` Wan2 Wan `json:"wan2"` - PortTable []*Port `json:"port_table" fakesize:"5"` + PortTable []*Port `fakesize:"5" json:"port_table"` NetworkTable NetworkTable `json:"network_table"` Uplink Uplink `json:"uplink"` Stat USGStat `json:"stat"` @@ -76,12 +76,12 @@ type Uplink struct { Drops FlexInt `json:"drops"` Enable FlexBool `json:"enable,omitempty"` FullDuplex FlexBool `json:"full_duplex"` - Gateways []string `json:"gateways,omitempty" fakesize:"5"` - IP string `json:"ip" fake:"{ipv4address}"` + Gateways []string `fakesize:"5" json:"gateways,omitempty"` + IP string `fake:"{ipv4address}" json:"ip"` Latency FlexInt `json:"latency"` Mac string `json:"mac,omitempty"` MaxSpeed FlexInt `json:"max_speed"` - Name string `json:"name" fake:"{animal}"` + Name string `fake:"{animal}" json:"name"` Nameservers []string `json:"nameservers"` Netmask string `json:"netmask"` NumPort FlexInt `json:"num_port"` @@ -115,19 +115,19 @@ type Uplink struct { type Wan struct { Autoneg FlexBool `json:"autoneg"` BytesR FlexInt `json:"bytes-r"` - DNS []string `json:"dns" fakesize:"5"` // may be deprecated + DNS []string `fakesize:"5" json:"dns"` // may be deprecated Enable FlexBool `json:"enable"` FlowctrlRx FlexBool `json:"flowctrl_rx"` FlowctrlTx FlexBool `json:"flowctrl_tx"` FullDuplex FlexBool `json:"full_duplex"` Gateway string `json:"gateway"` // may be deprecated - IP string `json:"ip" fake:"{ipv4address}"` + IP string `fake:"{ipv4address}" json:"ip"` Ifname string `json:"ifname"` IsUplink FlexBool `json:"is_uplink"` - Mac string `json:"mac" fake:"{macaddress}"` + Mac string `fake:"{macaddress}" json:"mac"` MaxSpeed FlexInt `json:"max_speed"` Media string `json:"media"` - Name string `json:"name" fake:"{animal}"` + Name string `fake:"{animal}" json:"name"` Netmask string `json:"netmask"` // may be deprecated NumPort int `json:"num_port"` PortIdx int `json:"port_idx"` @@ -172,12 +172,12 @@ type SpeedtestStatus struct { type SpeedtestServer struct { Cc string `json:"cc"` - City string `json:"city" fake:"{city}"` - Country string `json:"country" fake:"{country}"` + City string `fake:"{city}" json:"city"` + Country string `fake:"{country}" json:"country"` Lat FlexInt `json:"lat"` Lon FlexInt `json:"lon"` Provider string `json:"provider"` - ProviderURL string `json:"provider_url" fake:"{url}"` + ProviderURL string `fake:"{url}" json:"provider_url"` } // SystemStats is system info for a UDM, USG, USW. @@ -187,7 +187,7 @@ type SystemStats struct { Uptime FlexInt `json:"uptime"` // This exists on at least USG4, may others, maybe not. // {"Board (CPU)":"51 C","Board (PHY)":"51 C","CPU":"72 C","PHY":"77 C"} - Temps map[string]FlexTemp `json:"temps,omitempty" fakesize:"5"` + Temps map[string]FlexTemp `fakesize:"5" json:"temps,omitempty"` } // SysStats is load info for a UDM, USG, USW. diff --git a/usw.go b/usw.go index 8b8a144..3e0cab6 100644 --- a/usw.go +++ b/usw.go @@ -98,7 +98,7 @@ type USW struct { TotalMaxPower FlexInt `json:"total_max_power"` TwoPhaseAdopt FlexBool `json:"two_phase_adopt"` TxBytes FlexInt `json:"tx_bytes"` - Type string `json:"type" fake:"{randomstring:[usg,pdu]}"` + Type string `fake:"{randomstring:[usg,pdu]}" json:"type"` Unsupported FlexBool `json:"unsupported"` UnsupportedReason FlexInt `json:"unsupported_reason"` Upgradable FlexBool `json:"upgradable,omitempty"` @@ -140,7 +140,7 @@ type USWStat struct { // Sw is a subtype of USWStat to make unmarshalling of different controller versions possible. type Sw struct { - SiteID string `json:"site_id" fake:"{uuid}"` + SiteID string `fake:"{uuid}" json:"site_id"` O string `json:"o"` Oid string `json:"oid"` Sw string `json:"sw"` diff --git a/uxg.go b/uxg.go index 51cf0b8..dd27b4d 100644 --- a/uxg.go +++ b/uxg.go @@ -20,13 +20,13 @@ type UXG struct { ConnectionNetworkName string `json:"connection_network_name"` ConnectedAt FlexInt `json:"connected_at"` ConsideredLostAt FlexInt `json:"considered_lost_at"` - DeviceID string `json:"device_id" fake:"{uuid}"` + DeviceID string `fake:"{uuid}" json:"device_id"` DisplayableVersion string `json:"displayable_version"` - DownlinkTable []*DownlinkTable `json:"downlink_table" fakesize:"5"` - EthernetOverrides []*EthernetOverrides `json:"ethernet_overrides" fakesize:"5"` - EthernetTable []*EthernetTable `json:"ethernet_table" fakesize:"5"` + DownlinkTable []*DownlinkTable `fakesize:"5" json:"downlink_table"` + EthernetOverrides []*EthernetOverrides `fakesize:"5" json:"ethernet_overrides"` + EthernetTable []*EthernetTable `fakesize:"5" json:"ethernet_table"` FwCaps FlexInt `json:"fw_caps"` - GeoInfo map[string]*GeoInfo `json:"geo_info" fakesize:"5"` + GeoInfo map[string]*GeoInfo `fakesize:"5" json:"geo_info"` GuestKicks FlexInt `json:"guest_kicks"` GuestLanNumSta FlexInt `json:"guest-lan-num_sta"` GuestNumSta FlexInt `json:"guest-num_sta"` @@ -38,10 +38,10 @@ type UXG struct { HasTemperature FlexBool `json:"has_temperature"` HashID string `json:"hash_id"` HwCaps FlexInt `json:"hw_caps"` - ID string `json:"_id" fake:"{uuid}"` - IP string `json:"ip" fake:"{ipv4address}"` - InformIP string `json:"inform_ip" fake:"{ipv4address}"` - InformURL string `json:"inform_url" fake:"{url}"` + ID string `fake:"{uuid}" json:"_id"` + IP string `fake:"{ipv4address}" json:"ip"` + InformIP string `fake:"{ipv4address}" json:"inform_ip"` + InformURL string `fake:"{url}" json:"inform_url"` Internet FlexBool `json:"internet"` IsAccessPoint FlexBool `json:"is_access_point"` KernelVersion string `json:"kernel_version"` @@ -61,7 +61,7 @@ type UXG struct { LedState *LedState `json:"led_state"` LicenseState string `json:"license_state"` Locating FlexBool `json:"locating"` - Mac string `json:"mac" fake:"{macaddress}"` + Mac string `fake:"{macaddress}" json:"mac"` ManufacturerID FlexInt `json:"manufacturer_id"` MinInformIntervalSeconds FlexInt `json:"min_inform_interval_seconds"` Model string `json:"model"` @@ -87,7 +87,7 @@ type UXG struct { RxBytes FlexInt `json:"rx_bytes"` Serial string `json:"serial"` SetupID string `json:"setup_id"` - SiteID string `json:"site_id" fake:"{uuid}"` + SiteID string `fake:"{uuid}" json:"site_id"` SiteName string `json:"-"` SourceName string `json:"-"` SpeedtestStatus SpeedtestStatus `json:"speedtest-status"` @@ -106,7 +106,7 @@ type UXG struct { Temperatures []Temperature `json:"temperatures"` TwoPhaseAdopt FlexBool `json:"two_phase_adopt"` TxBytes FlexInt `json:"tx_bytes"` - Type string `json:"type" fake:"{lexify:uxg}"` + Type string `fake:"{lexify:uxg}" json:"type"` UdapiCaps FlexInt `json:"udapi_caps"` UnderscoreUptime FlexInt `json:"_uptime"` Unsupported FlexBool `json:"unsupported"` @@ -141,12 +141,12 @@ type LedState struct { // GeoInfo is incuded with certain devices. type GeoInfo struct { Accuracy FlexInt `json:"accuracy"` - Address string `json:"address" fake:"{address}"` + Address string `fake:"{address}" json:"address"` Asn FlexInt `json:"asn"` - City string `json:"city" fake:"{city}"` + City string `fake:"{city}" json:"city"` ContinentCode string `json:"continent_code"` CountryCode string `json:"country_code"` - CountryName string `json:"country_name" fake:"{country}"` + CountryName string `fake:"{country}" json:"country_name"` IspName string `json:"isp_name"` IspOrganization string `json:"isp_organization"` Latitude FlexInt `json:"latitude"` From d279e92e06a945b880b13c85b8c727e96bc115f4 Mon Sep 17 00:00:00 2001 From: Cody Lee Date: Thu, 27 Jul 2023 09:07:47 -0500 Subject: [PATCH 2/4] bump go version and golangci-lint version --- .github/workflows/build.yml | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e92f078..4eb3ec2 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -14,7 +14,7 @@ jobs: test: strategy: matrix: - go: [1.19] + go: [1.20] os: [ubuntu-latest] runs-on: ${{ matrix.os }} steps: @@ -33,7 +33,7 @@ jobs: lint: strategy: matrix: - go: [1.19] + go: [1.20] os: [ubuntu-latest] name: lint runs-on: ${{ matrix.os }} @@ -47,13 +47,4 @@ jobs: uses: golangci/golangci-lint-action@v3 with: # Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version. - version: v1.50.1 - # Optional: working directory, useful for monorepos - # working-directory: somedir - - # Optional: golangci-lint command line arguments. - # args: --issues-exit-code=0 - args: --timeout=3m - - # Optional: show only new issues if it's a pull request. The default value is `false`. - # only-new-issues: true + version: v1.53 From 79fe10391f9ba786ee0019144d27ba7de1e55927 Mon Sep 17 00:00:00 2001 From: Cody Lee Date: Thu, 27 Jul 2023 09:11:30 -0500 Subject: [PATCH 3/4] mirror build completely --- .github/workflows/build.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4eb3ec2..bf93056 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,6 +1,6 @@ name: Build -on: +on: - pull_request permissions: @@ -14,8 +14,8 @@ jobs: test: strategy: matrix: - go: [1.20] - os: [ubuntu-latest] + go: ["1.20"] + os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v3 @@ -33,7 +33,7 @@ jobs: lint: strategy: matrix: - go: [1.20] + go: ["1.20"] os: [ubuntu-latest] name: lint runs-on: ${{ matrix.os }} From 637233dc98ed905e08dd3a94df36404e02f1b9d5 Mon Sep 17 00:00:00 2001 From: Cody Lee Date: Thu, 27 Jul 2023 09:16:04 -0500 Subject: [PATCH 4/4] remove windows due to port binding issues in test add release to give a better release experience --- .github/workflows/build.yml | 2 +- .github/workflows/release.yml | 35 +++++++++++++++++++++++++++++++++++ .goreleaser.yaml | 2 ++ 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/release.yml create mode 100644 .goreleaser.yaml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index bf93056..638223f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -15,7 +15,7 @@ jobs: strategy: matrix: go: ["1.20"] - os: [ubuntu-latest, macos-latest, windows-latest] + os: [ubuntu-latest, macos-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v3 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..758037f --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,35 @@ +name: Release + +on: + push: + # run only against tags + tags: + - '*' + +permissions: + contents: write + packages: write + +jobs: + release: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - run: git fetch --force --tags + - uses: actions/setup-go@v3 + with: + go-version: '>=1.20.5' + cache: true + - uses: goreleaser/goreleaser-action@v4 + with: + # either 'goreleaser' (default) or 'goreleaser-pro': + distribution: goreleaser-pro + version: latest + args: release --clean + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Your GoReleaser Pro key, if you are using the 'goreleaser-pro' + # distribution: + GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }} diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 0000000..10b9449 --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,2 @@ +builds: +- skip: true \ No newline at end of file