github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/com/com.go (about)

     1  package com
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/base64"
     6  	"encoding/json"
     7  	"fmt"
     8  	"io/ioutil"
     9  	"net"
    10  	"net/http"
    11  	"os"
    12  	"reflect"
    13  	"runtime"
    14  	"strconv"
    15  
    16  	"database/sql"
    17  
    18  	"github.com/mdaxf/iac-signalr/signalr"
    19  	"go.mongodb.org/mongo-driver/mongo"
    20  )
    21  
    22  var Instance string
    23  var InstanceType string
    24  var InstanceName string
    25  var InstanceID string
    26  var SingalRConfig map[string]interface{}
    27  var TransactionTimeout int
    28  var DBTransactionTimeout int
    29  
    30  var IACDBConn *DBConn
    31  var IACDocDBConn *DocDB
    32  
    33  var MongoDBClients []*mongo.Client
    34  var IACMessageBusClient signalr.Client
    35  
    36  var NodeHeartBeats map[string]interface{}
    37  
    38  var IACNode map[string]interface{}
    39  
    40  // HeartbeatChecker is an interface that defines the required methods
    41  // for performing heartbeat checks on various services.
    42  type HeartbeatChecker interface {
    43  	// Ping checks the health or connectivity of the service.
    44  	// It returns an error if the service is unhealthy or disconnected.
    45  	Ping() error
    46  
    47  	// Connect establishes a connection to the service.
    48  	Connect() error
    49  
    50  	// Disconnect closes the connection to the service.
    51  	Disconnect() error
    52  
    53  	// Reconnect attempts to reconnect to the service.
    54  	ReConnect() error
    55  }
    56  
    57  type DocDB struct {
    58  	MongoDBClient        *mongo.Client
    59  	MongoDBDatabase      *mongo.Database
    60  	MongoDBCollection_TC *mongo.Collection
    61  	/*
    62  	 */
    63  	DatabaseType       string
    64  	DatabaseConnection string
    65  	DatabaseName       string
    66  }
    67  
    68  type DBConn struct {
    69  	DBType       string
    70  	DBConnection string
    71  	DBName       string
    72  	DB           *sql.DB
    73  	MaxIdleConns int
    74  	MaxOpenConns int
    75  }
    76  
    77  var ApiKey string
    78  
    79  func ConverttoInt(value interface{}) int {
    80  	return ConverttoIntwithDefault(value, 0)
    81  }
    82  
    83  func ConverttoIntwithDefault(value interface{}, defaultvalue int) int {
    84  	if value == nil {
    85  		return defaultvalue
    86  	}
    87  	switch value.(type) {
    88  	case int:
    89  		return value.(int)
    90  	case float64:
    91  		return int(value.(float64))
    92  	case string:
    93  		temp, err := strconv.Atoi(value.(string))
    94  		if err != nil {
    95  			return defaultvalue
    96  		}
    97  		return temp
    98  	default:
    99  		return defaultvalue
   100  	}
   101  }
   102  
   103  func ConverttoFloat64(value interface{}) float64 {
   104  	return ConverttoFloat64withDefault(value, 0)
   105  }
   106  
   107  func ConverttoFloat64withDefault(value interface{}, defaultvalue float64) float64 {
   108  	if value == nil {
   109  		return defaultvalue
   110  	}
   111  	switch value.(type) {
   112  	case int:
   113  		return float64(value.(int))
   114  	case float64:
   115  		return value.(float64)
   116  	default:
   117  		return defaultvalue
   118  	}
   119  }
   120  
   121  func ConverttoBoolean(value interface{}) bool {
   122  	return ConverttoBooleanwithDefault(value, false)
   123  }
   124  
   125  func ConverttoBooleanwithDefault(value interface{}, defaultvalue bool) bool {
   126  	if value == nil {
   127  		return defaultvalue
   128  	}
   129  	switch value.(type) {
   130  	case bool:
   131  		return value.(bool)
   132  	case int:
   133  		return value.(int) != 0
   134  	case float64:
   135  		return value.(float64) != 0
   136  	default:
   137  		return defaultvalue
   138  	}
   139  }
   140  
   141  func ConverttoString(value interface{}) string {
   142  	return ConverttoStringwithDefault(value, "")
   143  }
   144  
   145  func ConverttoStringwithDefault(value interface{}, defaultvalue string) string {
   146  	if value == nil {
   147  		return defaultvalue
   148  	}
   149  
   150  	if str, ok := value.(string); ok {
   151  		return str
   152  	} else {
   153  		switch v := value.(type) {
   154  		case string:
   155  			return v
   156  		case int:
   157  			return strconv.Itoa(v)
   158  		case int64:
   159  			return strconv.FormatInt(v, 10)
   160  		case uint:
   161  			return strconv.FormatUint(uint64(v), 10)
   162  		case float64:
   163  			return strconv.FormatFloat(v, 'f', -1, 64)
   164  		default:
   165  			return fmt.Sprintf("%v", value)
   166  		}
   167  	}
   168  }
   169  
   170  func ConvertstructToMap(input interface{}) map[string]interface{} {
   171  	result := make(map[string]interface{})
   172  
   173  	val := reflect.ValueOf(input)
   174  	typ := reflect.TypeOf(input)
   175  
   176  	// Check if the input is a struct
   177  	if val.Kind() == reflect.Struct {
   178  		for i := 0; i < val.NumField(); i++ {
   179  			field := val.Field(i)
   180  			fieldName := typ.Field(i).Name
   181  
   182  			// Add the field to the map
   183  			result[fieldName] = field.Interface()
   184  		}
   185  	}
   186  
   187  	return result
   188  }
   189  
   190  func ConvertbytesToMap(data []byte) (map[string]interface{}, error) {
   191  	var result map[string]interface{}
   192  
   193  	err := json.Unmarshal(data, &result)
   194  	if err != nil {
   195  		return nil, err
   196  	}
   197  
   198  	return result, nil
   199  }
   200  
   201  func DecodeBase64String(input string) (string, error) {
   202  	decodedData, err := base64.StdEncoding.DecodeString(input)
   203  	if err != nil {
   204  		return "", err
   205  	}
   206  	return string(decodedData), nil
   207  }
   208  
   209  func Convertbase64ToMap(input string) (map[string]interface{}, error) {
   210  	// Decode Base64 string
   211  	decodedData, err := base64.StdEncoding.DecodeString(input)
   212  	if err != nil {
   213  		return nil, err
   214  	}
   215  	println("data:", string(decodedData))
   216  	return ConvertbytesToMap(decodedData)
   217  	// Unmarshal JSON data
   218  	var resultMap map[string]interface{}
   219  	err = json.Unmarshal(decodedData, &resultMap)
   220  	if err != nil {
   221  		return nil, err
   222  	}
   223  
   224  	return resultMap, nil
   225  }
   226  
   227  func ConvertInterfaceToString(input interface{}) (string, error) {
   228  	jsondata, err := json.Marshal(input)
   229  	if err != nil {
   230  		fmt.Println(fmt.Sprintf("Failed to convert json to map: %v", err))
   231  		return "", err
   232  	}
   233  	return DecodeBase64String(fmt.Sprintf("%s", jsondata))
   234  }
   235  
   236  func ConvertMapToString(data map[string]interface{}) (string, error) {
   237  	// Marshal the map to JSON
   238  	jsonBytes, err := json.Marshal(data)
   239  	if err != nil {
   240  		return "", err
   241  	}
   242  
   243  	// Convert the byte slice to a string
   244  	jsonString := string(jsonBytes)
   245  	return jsonString, nil
   246  }
   247  
   248  func CallWebService(url string, method string, data map[string]interface{}, headers map[string]string) (map[string]interface{}, error) {
   249  	var result map[string]interface{}
   250  	// Create a new HTTP client
   251  	client := &http.Client{}
   252  
   253  	bytesdata, err := json.Marshal(data)
   254  	if err != nil {
   255  		//	fmt.Error(fmt.Sprintf("Error:", err))
   256  		return nil, err
   257  	}
   258  
   259  	req, err := http.NewRequest(method, url, bytes.NewBuffer(bytesdata))
   260  
   261  	if err != nil {
   262  		//	fmt.Error("Error in WebServiceCallFunc.Execute: %s", err)
   263  		return nil, err
   264  	}
   265  	if headers != nil {
   266  		for key, value := range headers {
   267  			req.Header.Set(key, value)
   268  		}
   269  	}
   270  
   271  	resp, err := client.Do(req)
   272  	if err != nil {
   273  		//	fmt.Error("Error in WebServiceCallFunc.Execute: %s", err)
   274  		return nil, err
   275  	}
   276  	defer resp.Body.Close()
   277  
   278  	respBody, err := ioutil.ReadAll(resp.Body)
   279  	err = json.Unmarshal(respBody, &result)
   280  	if err != nil {
   281  		//	fmt.Error(fmt.Sprintf("Error:", err))
   282  		return nil, err
   283  	}
   284  	//	fmt.printf("Response data: %v", result)
   285  	return result, nil
   286  }
   287  
   288  func GetHostandIPAddress() (map[string]interface{}, error) {
   289  	hostname, err := os.Hostname()
   290  	if err != nil {
   291  		fmt.Println("Error getting hostname:", err)
   292  		return nil, err
   293  	}
   294  	fmt.Println("Hostname: %s", hostname)
   295  
   296  	addrs, err := net.InterfaceAddrs()
   297  	if err != nil {
   298  		fmt.Println("Error getting IP addresses:", err)
   299  		return nil, err
   300  	}
   301  	var ipnet *net.IPNet
   302  
   303  	for _, addr := range addrs {
   304  		if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
   305  			if ipnet.IP.To4() != nil {
   306  				fmt.Println("IPv4 address:", ipnet.IP.String())
   307  			} else {
   308  				fmt.Println("IPv6 address:", ipnet.IP.String())
   309  			}
   310  		}
   311  	}
   312  
   313  	osName := runtime.GOOS
   314  
   315  	nodedata := make(map[string]interface{})
   316  	nodedata["Host"] = hostname
   317  	nodedata["OS"] = osName
   318  
   319  	if ipnet != nil {
   320  		if ipnet.IP.To4() != nil {
   321  			nodedata["IPAddress"] = ipnet.IP.String()
   322  		}
   323  	}
   324  	return nodedata, nil
   325  }