Skip to content

Commit

Permalink
import modules from zenit repository
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicola Strappazzon C committed Oct 8, 2023
1 parent ade140f commit 4d2e316
Show file tree
Hide file tree
Showing 21 changed files with 922 additions and 2 deletions.
25 changes: 25 additions & 0 deletions cast/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cast
import (
"strconv"
"strings"
"time"
)

func StringToInt(value string) int {
Expand All @@ -12,3 +13,27 @@ func StringToInt(value string) int {
}
return i
}

func StringToInt64(value string) int64 {
i, err := strconv.ParseInt(strings.TrimSpace(value), 10, 64)
if err != nil {
return 0
}
return i
}

func StringToFloat64(value string) float64 {
i, err := strconv.ParseFloat(strings.TrimSpace(value), 64)
if err != nil {
return 0
}
return i
}

func ToDateTime(timestamp string, layout string) string {
t, err := time.Parse(layout, timestamp)
if err != nil {
return ""
}
return t.Format("2006-01-02 15:04:05")
}
30 changes: 30 additions & 0 deletions cast/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,33 @@ import (
func TestStringToInt(t *testing.T) {
assert.Equal(t, cast.StringToInt("123"), 123)
}

func TestStringToInt64(t *testing.T) {
expected := int64(1234)
result := cast.StringToInt64("1234")

if result != expected {
t.Error("Expected: int64(1234)")
}

result = cast.StringToInt64("abc")

if result != 0 {
t.Error("Expected: 0")
}

result = cast.StringToInt64("")

if result != 0 {
t.Error("Expected: 0")
}
}

func TestToDateTime(t *testing.T) {
expected := "2018-12-31 15:04:05"
result := cast.ToDateTime("2018-12-31T15:04:05 UTC", "2006-01-02T15:04:05 UTC")

if result != expected {
t.Error("Expected: 2018-12-31 15:04:05")
}
}
27 changes: 27 additions & 0 deletions exec/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package exec

import (
"fmt"
"os/exec"
"syscall"

"github.com/debeando/go-common/cast"
)

func PGrep(cmd string) int64 {
stdout, _ := Command(fmt.Sprintf("/usr/bin/pgrep -f '%s'", cmd))

return cast.StringToInt64(stdout)
}

func Command(cmd string) (stdout string, exitcode int) {
out, err := exec.Command("/bin/bash", "-c", cmd).Output()

if exitError, ok := err.(*exec.ExitError); ok {
ws := exitError.Sys().(syscall.WaitStatus)
exitcode = ws.ExitStatus()
}

stdout = string(out[:])
return
}
27 changes: 27 additions & 0 deletions file/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,20 @@ package file

import (
"io/ioutil"
"os"
"path/filepath"

"github.com/debeando/go-common/cast"
)

func Exist(path string) bool {
info, err := os.Stat(path)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}

func Read(path string) []byte {
c, _ := ioutil.ReadFile(path)
return c
Expand All @@ -14,10 +25,26 @@ func ReadAsString(path string) string {
return string(Read(path))
}

func ReadExpandEnv(path string) []byte {
return []byte(os.ExpandEnv(ReadAsString(path)))
}

func ReadExpandEnvAsString(path string) string {
return string(ReadExpandEnv(path))
}

func Name(n string) string {
return n[:len(n)-len(filepath.Ext(n))]
}

func Dir(path string) string {
return filepath.Dir(path)
}

func GetInt64(path string) int64 {
lines := ReadAsString(path)
if len(lines) > 0 {
return cast.StringToInt64(lines)
}
return 0
}
31 changes: 31 additions & 0 deletions file/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package file_test

import (
"os"
"reflect"
"testing"

"github.com/debeando/go-common/file"
)

var wd string

func TestMain(m *testing.M) {
wd, _ = os.Getwd()
}

func TestGetInt64FromFile(t *testing.T) {
expected := int64(1234567890)
result := common.GetInt64FromFile(wd + "/../assets/tests/int64.txt")

if result != expected {
t.Error("Expected: int64(1234567890)")
}

expected = int64(0)
result = common.GetInt64FromFile(wd + "/../assets/tests/int64.log")

if result != expected {
t.Error("Expected: int64(0)")
}
}
33 changes: 33 additions & 0 deletions http/http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package http

import (
"net/http"
"strings"

"github.com/debeando/go-common/log"
)

func Post(uri string, data string, headers map[string]string) int {
req, err := http.NewRequest(
"POST",
uri,
strings.NewReader(data),
)
if err != nil {
log.ErrorWithFields("HTTP(s) Client", log.Fields{"error": err})
}

for key, value := range headers {
req.Header.Add(key, value)
}

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.ErrorWithFields("HTTP(s) Client", log.Fields{"error": err})
return 520 // Status code 520 Unknown Error
}
defer resp.Body.Close()

return resp.StatusCode
}
33 changes: 33 additions & 0 deletions http/http_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package http_test

import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"

test "github.com/debeando/go-common/http"
)

func TestPost(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
t.Errorf("Expected 'POST' request, got '%s'", r.Method)
}

body, _ := ioutil.ReadAll(r.Body)

if string(body) != "foo" {
t.Errorf("Expected request to 'foo', got '%s'", string(body))
}

w.WriteHeader(http.StatusOK)
}))
defer ts.Close()

response := test.Post(ts.URL, "foo", nil)

if response != 200 {
t.Errorf("Expected: '200', got: '%v'.", response)
}
}
22 changes: 22 additions & 0 deletions maps/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package maps

import (
"sort"
)

func Keys(v []map[string]string) (keys []string) {
if len(v) > 0 {
for key := range v[0] {
keys = append(keys, key)
}
sort.Strings(keys)
}
return
}

func In(key string, list map[string]string) bool {
if _, ok := list[key]; ok {
return true
}
return false
}
29 changes: 29 additions & 0 deletions maps/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package maps_test

import (
"testing"

"github.com/debeando/go-common/maps"
)

func TestKeys(t *testing.T) {
result := maps.Keys([]map[string]string{{"foo": "a", "bar": "1"}, {"foo": "b", "bar": "2"}})
expected := []string{"foo", "bar"}

if !reflect.DeepEqual(result, expected) {
t.Error("Expected: []string{\"foo\", \"bar\"}")
}
}

func TestIn(t *testing.T) {
expected := make(map[string]string)
expected["test"] = "test"

if !maps.In("test", expected) {
t.Error("Expected: true")
}

if maps.In("foo", expected) {
t.Error("Expected: false")
}
}
10 changes: 10 additions & 0 deletions math/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package math

func Percentage(value int64, max uint64) float64 {
v := float64(value)
m := float64(max)
if v >= 0 && m > 0 {
return (v / m) * 100
}
return 0
}
4 changes: 2 additions & 2 deletions mysql/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ type Connection struct {

var instance = make(map[string]*Connection)

func Instance(name string) *Connection {
func GetInstance(name string) *Connection {
if instance[name] == nil {
instance[name] = &Connection{}
instance[name].Name = name
Expand All @@ -52,7 +52,7 @@ func (c *Connection) Connect() error {
}

func (c *Connection) Query(query string) (map[int]map[string]string, error) {
log.DebugWithFields("MySQL execute.", log.Fields{
log.DebugWithFields("MySQL execute", log.Fields{
"Query": query,
})

Expand Down
Loading

0 comments on commit 4d2e316

Please sign in to comment.