Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
imperiuse committed Jan 26, 2021
1 parent 8c5fc09 commit 145fe40
Show file tree
Hide file tree
Showing 25 changed files with 146 additions and 125 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
.idea
.idea/*
.idea/watcherTasks.xml
2 changes: 1 addition & 1 deletion .idea/watcherTasks.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2018 Arseny Sazanov
Copyright (c) 2018-2021 Arseny Sazanov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# golang_lib
Helpfull goland lib for variouse things
Helpfully goland lib

Example for various stuff

### Install

Expand Down
5 changes: 5 additions & 0 deletions archive/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# There are my first micro library

Today in 2021 I understand that is not good example of go code... =(

So, don't use this in your production. Thx!
2 changes: 1 addition & 1 deletion archive/colormap/colormap.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"fmt"
"strconv"

"github.com/imperiuse/golib/concat"
"github.com/imperiuse/golib/archive/concat"
)

// CSN - ColorSchemeNumber
Expand Down
2 changes: 1 addition & 1 deletion archive/colors/colors.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package colors
import (
"fmt"

"github.com/imperiuse/golib/colormap"
"github.com/imperiuse/golib/archive/colormap"
)

var (
Expand Down
2 changes: 1 addition & 1 deletion archive/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"time"

"github.com/imperiuse/golib/archive/colormap"
"github.com/imperiuse/golib/concat"
"github.com/imperiuse/golib/archive/concat"
)

// LoggerBean - Bean описывающий настройки логера
Expand Down
2 changes: 1 addition & 1 deletion archive/postgres/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"strconv"
"time"

"github.com/imperiuse/golib/concat"
"github.com/imperiuse/golib/archive/concat"

l "github.com/imperiuse/golib/archive/logger"
"github.com/imperiuse/golib/email"
Expand Down
2 changes: 1 addition & 1 deletion archive/telnet/telnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (

"github.com/sirupsen/logrus"

"github.com/imperiuse/golib/server"
"github.com/imperiuse/golib/archive/server"
"github.com/pkg/errors"
)

Expand Down
8 changes: 4 additions & 4 deletions dirhelper/dirhelper.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,8 @@ func CopyDir(src string, dst string) error {
return nil
}

// CreateDir - создает новую директорию (есть проверка на существование директории, если нет - создает)
func CreateDir(dir string) error {
// MakeDir - создает новую директорию (есть проверка на существование директории, если нет - создает)
func MakeDir(dir string) error {
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err = os.MkdirAll(dir, os.ModePerm); err != nil {
return err
Expand Down Expand Up @@ -120,8 +120,8 @@ func CleanDir(dir string) (err error) {
return
}

// ListSubdirs - получает список поддиректорий в текущей директории
func ListSubdirs(src string) ([]string, error) {
// ListSubeditors - получает список поддиректорий в текущей директории
func ListSubeditors(src string) ([]string, error) {
fds, err := ioutil.ReadDir(src)
if err != nil {
return nil, errors.WithMessage(err, fmt.Sprintf("can't ioutil.ReadDir for dir:%s", src))
Expand Down
6 changes: 3 additions & 3 deletions dispatcher/dispatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func Create(timeout int, onlyNew []string, renew []string) (*Dispatcher, error)
return &d, nil
}

// NextNewAccountID - возращает следующий аккаунт id доступный для выпуска новых сертов, и флаг - успех/нет
// NextNewAccountID - возвращает следующий аккаунт id доступный для выпуска новых сертов, и флаг - успех/нет
func (d *Dispatcher) NextNewAccountID(ctx context.Context) (string, bool) {

ctxWithTimeout, cancelFunction := context.WithTimeout(ctx, time.Duration(d.timeoutWaitID)*time.Second)
Expand All @@ -70,7 +70,7 @@ func (d *Dispatcher) NextNewAccountID(ctx context.Context) (string, bool) {
}
}

// NextRenewAccountID - возращает следующий аккаунт id доступный для перевыпуска сертов, и флаг - успех/нет
// NextRenewAccountID - возвращает следующий аккаунт id доступный для перевыпуска сертов, и флаг - успех/нет
func (d *Dispatcher) NextRenewAccountID(ctx context.Context) (string, bool) {

ctxWithTimeout, cancelFunction := context.WithTimeout(ctx, time.Duration(d.timeoutWaitID)*time.Second)
Expand Down Expand Up @@ -98,7 +98,7 @@ func (d *Dispatcher) FreeNewAccountID(ctx context.Context, id string) error {
}
}

// FreeRenewAccountID - возращает использованный id в канал renew accounts id
// FreeRenewAccountID - возвращает использованный id в канал renew accounts id
func (d *Dispatcher) FreeRenewAccountID(ctx context.Context, id string) error {

ctxWithTimeout, cancelFunction := context.WithTimeout(ctx, time.Duration(deferDuration)*time.Second)
Expand Down
5 changes: 1 addition & 4 deletions email/email.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (

"github.com/sirupsen/logrus"

"github.com/imperiuse/golib/concat"
"github.com/imperiuse/golib/archive/concat"
)

// MailBean - all settings for email package in Bean-like struct
Expand Down Expand Up @@ -65,13 +65,11 @@ func (m *MailBean) SendEmails(body string) error {

// sendEmail - send one email
func (m *MailBean) sendEmail(to mail.Address, subj, body string) (err error) {
// Setup headers
headers := make(map[string]string)
headers["from"] = m.from.String()
headers["to"] = to.String()
headers["Subject"] = subj

// Setup message
message := ""
for k, v := range headers {
message = concat.Strings(message, fmt.Sprintf("%s: %s\r\n", k, v))
Expand Down Expand Up @@ -117,7 +115,6 @@ func (m *MailBean) sendEmail(to mail.Address, subj, body string) (err error) {
m.log.WithError(err).Error("client.Rcpt(to.Address)")
}

// Data
w, err := client.Data()
if err != nil {
m.log.WithError(err).Error("client.Data")
Expand Down
2 changes: 1 addition & 1 deletion filters/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## Intro

The idea of ​​the package is to enable the quick implementation of various custom filters for an HTTP request.
The idea of the package is to enable the quick implementation of various custom filters for an HTTP request.

The package already implements all the default methods of the interface filter `Filterer` in the base filter` BaseFilter`.

Expand Down
9 changes: 5 additions & 4 deletions filters/order.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package filters

import (
"fmt"
"net/http"
)

Expand All @@ -23,6 +22,10 @@ type OrderFilters struct {
filters []Filterer
}

var emptyFilterHandler = func(w http.ResponseWriter, r *http.Request) {
return
}

// GetOrderFilters - Get order of filters
//@return
// []string - slice of string (name filters)
Expand Down Expand Up @@ -65,8 +68,6 @@ func (filterOrder *OrderFilters) GetFilterN(n int) Filterer {
}

// GenerateFilteredHandleFunc - Generate func - handle fun - filtered handle func of action
// ATTENTION CAN PANIC!
//nolint
// @param
// handleFunc func(http.ResponseWriter, *http.Request) - handle of action
// @return
Expand All @@ -77,5 +78,5 @@ func (filterOrder *OrderFilters) GenerateFilteredHandleFunc(handleFunc func(http
StartFilter.Run(w, r, handleFunc)
}
}
panic(fmt.Errorf("`GenerateFilteredHandleFunc()` --> fo.GetFilterN(0) return nil"))
return emptyFilterHandler
}
15 changes: 9 additions & 6 deletions humanize/humanize.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ import (
"strings"
)

func logn(n, b float64) float64 {
func logN(n, b float64) float64 {
return math.Log(n) / math.Log(b)
}

func HumValue(s uint64, base float64, sizes []string) string {
if s < 10 {
return fmt.Sprintf("%d B", s)
}
e := math.Floor(logn(float64(s), base))
e := math.Floor(logN(float64(s), base))
suffix := sizes[int(e)]
val := math.Floor(float64(s)/math.Pow(base, e)*10+0.5) / 10
f := "%.0f %s"
Expand All @@ -26,16 +26,19 @@ func HumValue(s uint64, base float64, sizes []string) string {
return fmt.Sprintf(f, val, suffix)
}

var (
sufShortSI = []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
sufLongSI = []string{"byte", "Kbyte", "Mbyte", "Gbyte", "Tbyte", "Pbyte", "Ebyte"}
)

// produces a human readable representation of an SI size. (82854982) -> 83 MB
func BytesSi(s uint64) string {
sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
return HumValue(s, 1000, sizes)
return HumValue(s, 1000, sufShortSI)
}

// produces a human readable representation of an IEC size. (82854982) -> 79 MiB
func Bytes(s uint64) string {
sizes := []string{"byte", "Kbyte", "Mbyte", "Gbyte", "Tbyte", "Pbyte", "Ebyte"}
return HumValue(s, 1024, sizes)
return HumValue(s, 1024, sufLongSI)
}

func Comma(v int64) string {
Expand Down
6 changes: 3 additions & 3 deletions inet/inet.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ func Be64toh(i uint64) uint64 {
return binary.BigEndian.Uint64((*(*[8]byte)(unsafe.Pointer(&i)))[:])
}

func InetAddr(s string) uint32 {
func Addr(s string) uint32 {
return binary.BigEndian.Uint32(net.ParseIP(s).To4())
}

func InetNtoa(p unsafe.Pointer) string {
func Ntoa4(p unsafe.Pointer) string {
return net.IP((*(*[net.IPv4len]byte)(p))[:]).String()
}

func Inet6Ntoa(p unsafe.Pointer) string {
func Ntoa6(p unsafe.Pointer) string {
return net.IP((*(*[net.IPv6len]byte)(p))[:]).String()
}
16 changes: 9 additions & 7 deletions jsonnocomment/jsonnocomment.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,21 @@ import (
"io/ioutil"
)

// ReadFileAndCleanComment - Функция чтения JSON файла и удаления из него закоментированных строк и блок (комментарии согласно правилам С/С++)
// ReadFileAndCleanComment - Функция чтения JSON файла и удаления из него закомментированных строк и блок
// (comments style like С/С++)
func ReadFileAndCleanComment(pathFile string) (cleanFile []byte, err error) {
// Чтение из file по pathFile
file, err := ioutil.ReadFile(pathFile)
if err != nil {
return nil, err
}

l := len(file)
// Создаем байтовый массив размера прочитанного чтобы избежать перевыделения памяти
cleanFile = make([]byte, l)
var commentLine bool // признак комментариев (закоментирована вся линия // ТУТ КОМЕНТ ДО КОНЦА СТРОЧКИ\n)
var commentBlock bool // признак комментариев (закоментирован только блок /* КОММЕНТ ТОЛЬКО ТУТ*/)
var j int // текущий индекс для заполнения среза cleanFile
cleanFile = make([]byte, l) // Создаем байтовый массив размера прочитанного чтобы избежать перевыделения памяти
var (
commentLine bool // признак комментариев (закомментирована вся линия // ТУТ КОМЕНТ ДО КОНЦА СТРОЧКИ\n)
commentBlock bool // признак комментариев (закомментирован только блок /* КОММЕНТ ТОЛЬКО ТУТ*/)
j int // текущий индекс для заполнения среза cleanFile
)
for i := 0; i < l; i++ {
c := file[i]
switch c {
Expand Down
2 changes: 1 addition & 1 deletion reflect/gobeans/gobeans.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import (
"github.com/pkg/errors"

"github.com/imperiuse/golib/archive/concat"
"github.com/imperiuse/golib/cast"
"github.com/imperiuse/golib/jsonnocomment"
"github.com/imperiuse/golib/reflect/cast"
)

// Типы свойств по аналогии с JAVA BEANS
Expand Down
Loading

0 comments on commit 145fe40

Please sign in to comment.