123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- package stcknsqmsg
- import (
- "encoding/json"
- "fmt"
- "net"
- "os"
- "stck/stck-nsq-msg/msg"
- "github.com/denisbrodbeck/machineid"
- "github.com/go-viper/mapstructure/v2"
- )
- type StckNsqMsg struct {
- Type string `mapstructure:"type"`
- Data StckNsqMsgVariant `mapstructure:"data"`
- }
- type StckNsqMsgRaw struct {
- Type string `mapstructure:"type"`
- Data map[string]interface{} `mapstructure:"data"`
- }
- type StckNsqMsgVariant interface {
- MsgType() string
- }
- func (m *StckNsqMsg) ToString() (string, error) {
- b, err := json.Marshal(m)
- if err != nil {
- return "", err
- }
- return string(b), nil
- }
- func FromString(s string) (StckNsqMsg, error) {
- var rm StckNsqMsgRaw
- var m StckNsqMsg
- err := json.Unmarshal([]byte(s), &rm)
- if err != nil {
- return m, err
- }
- // Cast to strongly typed struct
- m.Type = rm.Type
- switch rm.Type {
- case msg.DeviceHeartbeatMsgType:
- var d msg.DeviceHeartbeatMsg
- err = mapstructure.Decode(rm.Data, &d)
- if err != nil {
- return m, err
- }
- m.Data = &d
- default:
- return m, fmt.Errorf("unknown message type: %s", rm.Type)
- }
- return m, nil
- }
- func DeviceIdMatches(id1, id2 string) bool {
- return id1 == id2 || id1 == "*" || id2 == "*"
- }
- func GetLocalIP() (net.IP, error) {
- ifaces, err := net.Interfaces()
- if err != nil {
- return nil, err
- }
- for _, iface := range ifaces {
- addrs, err := iface.Addrs()
- if err != nil {
- return nil, err
- }
- for _, addr := range addrs {
- var ip net.IP
- switch v := addr.(type) {
- case *net.IPNet:
- ip = v.IP
- case *net.IPAddr:
- ip = v.IP
- }
- if ip == nil || ip.IsLoopback() {
- continue
- }
- ip = ip.To4()
- if ip == nil {
- continue // not an ipv4 address
- }
- return ip, nil
- }
- }
- return nil, fmt.Errorf("no non-loopback IP address found")
- }
- func MakeUniqueMachineID() string {
- ip, err := GetLocalIP()
- if err != nil {
- fmt.Fprintf(os.Stderr, "get local IP failed: %v\n", err)
- }
- machineid, err := machineid.ProtectedID("unique")
- if err != nil {
- fmt.Fprintf(os.Stderr, "get machine ID failed: %v\n", err)
- }
- return fmt.Sprintf("%s-%s", ip.String(), machineid)
- }
|