gofmt
Security / scan (1.19) (push) Successful in 5m28s Details
Security / scan (1.20) (push) Successful in 5m4s Details
Security / scan (1.21) (push) Successful in 1m35s Details
Test / uint (1.19, ubuntu-latest) (push) Successful in 2m4s Details
Test / uint (1.20, ubuntu-latest) (push) Successful in 2m5s Details
Test / uint (1.21, ubuntu-latest) (push) Successful in 1m47s Details
Verify / lint (1.19) (push) Successful in 1m8s Details
Verify / lint (1.20) (push) Successful in 2m36s Details
Verify / lint (1.21) (push) Successful in 1m23s Details

This commit is contained in:
Akvicor 2024-01-23 23:02:08 +08:00
parent 8e2038a61e
commit 8fc73b3e59
34 changed files with 2955 additions and 2955 deletions

View File

@ -1,53 +1,53 @@
package util
import (
"encoding/base64"
"encoding/base64"
)
type Base64Result struct {
result string
err error
result string
err error
}
func (b *Base64Result) Bytes() []byte {
return []byte(b.result)
return []byte(b.result)
}
func (b *Base64Result) String() string {
return b.result
return b.result
}
func (b *Base64Result) Error() error {
return b.err
return b.err
}
func NewBase64Result(result string, err error) *Base64Result {
return &Base64Result{
result: result,
err: err,
}
return &Base64Result{
result: result,
err: err,
}
}
type Base64 struct{}
func NewBase64() *Base64 {
return &Base64{}
return &Base64{}
}
func (b *Base64) EncodeBytes(data []byte) *Base64Result {
return NewBase64Result(base64.StdEncoding.EncodeToString(data), nil)
return NewBase64Result(base64.StdEncoding.EncodeToString(data), nil)
}
func (b *Base64) EncodeString(str string) *Base64Result {
return NewBase64Result(base64.StdEncoding.EncodeToString([]byte(str)), nil)
return NewBase64Result(base64.StdEncoding.EncodeToString([]byte(str)), nil)
}
func (b *Base64) DecodeBytes(data []byte) *Base64Result {
res, err := base64.StdEncoding.DecodeString(string(data))
return NewBase64Result(string(res), err)
res, err := base64.StdEncoding.DecodeString(string(data))
return NewBase64Result(string(res), err)
}
func (b *Base64) DecodeString(str string) *Base64Result {
res, err := base64.StdEncoding.DecodeString(str)
return NewBase64Result(string(res), err)
res, err := base64.StdEncoding.DecodeString(str)
return NewBase64Result(string(res), err)
}

View File

@ -1,57 +1,57 @@
package util
import (
"bytes"
"fmt"
"testing"
"bytes"
"fmt"
"testing"
)
func TestBase64(t *testing.T) {
testString := "Akvicor"
testStringBase64 := "QWt2aWNvcg=="
if NewBase64().EncodeString(testString).String() != testStringBase64 {
t.Errorf("expected %s got %s", testStringBase64, NewBase64().EncodeString(testString).String())
}
if NewBase64().EncodeBytes([]byte(testString)).String() != testStringBase64 {
t.Errorf("expected %s got %s", testStringBase64, NewBase64().EncodeString(testString).String())
}
if !bytes.Equal(NewBase64().EncodeString(testString).Bytes(), []byte(testStringBase64)) {
t.Errorf("expected %v got %v", []byte(testStringBase64), NewBase64().EncodeString(testString).Bytes())
}
if NewBase64().DecodeString(testStringBase64).Error() != nil {
t.Errorf("decode got err: %v", NewBase64().DecodeString(testStringBase64).Error())
}
if NewBase64().DecodeString(testStringBase64).String() != testString {
t.Errorf("expected %s got %s", testStringBase64, NewBase64().EncodeString(testString).String())
}
if NewBase64().DecodeBytes([]byte(testStringBase64)).String() != testString {
t.Errorf("expected %s got %s", testStringBase64, NewBase64().EncodeString(testString).String())
}
if !bytes.Equal(NewBase64().DecodeString(testStringBase64).Bytes(), []byte(testString)) {
t.Errorf("expected %v got %v", []byte(testStringBase64), NewBase64().EncodeString(testString).Bytes())
}
testString := "Akvicor"
testStringBase64 := "QWt2aWNvcg=="
if NewBase64().EncodeString(testString).String() != testStringBase64 {
t.Errorf("expected %s got %s", testStringBase64, NewBase64().EncodeString(testString).String())
}
if NewBase64().EncodeBytes([]byte(testString)).String() != testStringBase64 {
t.Errorf("expected %s got %s", testStringBase64, NewBase64().EncodeString(testString).String())
}
if !bytes.Equal(NewBase64().EncodeString(testString).Bytes(), []byte(testStringBase64)) {
t.Errorf("expected %v got %v", []byte(testStringBase64), NewBase64().EncodeString(testString).Bytes())
}
if NewBase64().DecodeString(testStringBase64).Error() != nil {
t.Errorf("decode got err: %v", NewBase64().DecodeString(testStringBase64).Error())
}
if NewBase64().DecodeString(testStringBase64).String() != testString {
t.Errorf("expected %s got %s", testStringBase64, NewBase64().EncodeString(testString).String())
}
if NewBase64().DecodeBytes([]byte(testStringBase64)).String() != testString {
t.Errorf("expected %s got %s", testStringBase64, NewBase64().EncodeString(testString).String())
}
if !bytes.Equal(NewBase64().DecodeString(testStringBase64).Bytes(), []byte(testString)) {
t.Errorf("expected %v got %v", []byte(testStringBase64), NewBase64().EncodeString(testString).Bytes())
}
}
func ExampleNewBase64() {
testString := "Akvicor"
testStringBase64 := "QWt2aWNvcg=="
encodeS := NewBase64().EncodeString(testString)
fmt.Println(encodeS)
encodeB := NewBase64().EncodeBytes([]byte(testString))
fmt.Println(encodeB.String())
decodeS := NewBase64().DecodeString(testStringBase64)
if decodeS.Error() == nil {
fmt.Println(decodeS)
}
decodeB := NewBase64().DecodeBytes([]byte(testStringBase64))
fmt.Println(decodeB.Bytes())
// Output:
// QWt2aWNvcg==
// QWt2aWNvcg==
// Akvicor
// [65 107 118 105 99 111 114]
testString := "Akvicor"
testStringBase64 := "QWt2aWNvcg=="
encodeS := NewBase64().EncodeString(testString)
fmt.Println(encodeS)
encodeB := NewBase64().EncodeBytes([]byte(testString))
fmt.Println(encodeB.String())
decodeS := NewBase64().DecodeString(testStringBase64)
if decodeS.Error() == nil {
fmt.Println(decodeS)
}
decodeB := NewBase64().DecodeBytes([]byte(testStringBase64))
fmt.Println(decodeB.Bytes())
// Output:
// QWt2aWNvcg==
// QWt2aWNvcg==
// Akvicor
// [65 107 118 105 99 111 114]
}

124
bit.go
View File

@ -1,66 +1,66 @@
package util
func BitSet(b any, bit byte, set bool) {
switch data := b.(type) {
case *byte: // uint8
if set {
*data = *data | (byte(1) << bit)
} else {
*data = *data & (^(byte(1) << bit))
}
case *int8:
if set {
*data = *data | (int8(1) << bit)
} else {
*data = *data & (^(int8(1) << bit))
}
case *uint16:
if set {
*data = *data | (uint16(1) << bit)
} else {
*data = *data & (^(uint16(1) << bit))
}
case *int16:
if set {
*data = *data | (int16(1) << bit)
} else {
*data = *data & (^(int16(1) << bit))
}
case *uint32:
if set {
*data = *data | (uint32(1) << bit)
} else {
*data = *data & (^(uint32(1) << bit))
}
case *int32:
if set {
*data = *data | (int32(1) << bit)
} else {
*data = *data & (^(int32(1) << bit))
}
case *uint64:
if set {
*data = *data | (uint64(1) << bit)
} else {
*data = *data & (^(uint64(1) << bit))
}
case *int64:
if set {
*data = *data | (int64(1) << bit)
} else {
*data = *data & (^(int64(1) << bit))
}
case *uint:
if set {
*data = *data | (uint(1) << bit)
} else {
*data = *data & (^(uint(1) << bit))
}
case *int:
if set {
*data = *data | (int(1) << bit)
} else {
*data = *data & (^(int(1) << bit))
}
}
switch data := b.(type) {
case *byte: // uint8
if set {
*data = *data | (byte(1) << bit)
} else {
*data = *data & (^(byte(1) << bit))
}
case *int8:
if set {
*data = *data | (int8(1) << bit)
} else {
*data = *data & (^(int8(1) << bit))
}
case *uint16:
if set {
*data = *data | (uint16(1) << bit)
} else {
*data = *data & (^(uint16(1) << bit))
}
case *int16:
if set {
*data = *data | (int16(1) << bit)
} else {
*data = *data & (^(int16(1) << bit))
}
case *uint32:
if set {
*data = *data | (uint32(1) << bit)
} else {
*data = *data & (^(uint32(1) << bit))
}
case *int32:
if set {
*data = *data | (int32(1) << bit)
} else {
*data = *data & (^(int32(1) << bit))
}
case *uint64:
if set {
*data = *data | (uint64(1) << bit)
} else {
*data = *data & (^(uint64(1) << bit))
}
case *int64:
if set {
*data = *data | (int64(1) << bit)
} else {
*data = *data & (^(int64(1) << bit))
}
case *uint:
if set {
*data = *data | (uint(1) << bit)
} else {
*data = *data & (^(uint(1) << bit))
}
case *int:
if set {
*data = *data | (int(1) << bit)
} else {
*data = *data & (^(int(1) << bit))
}
}
}

View File

@ -1,99 +1,99 @@
package util
import (
"fmt"
"testing"
"fmt"
"testing"
)
func TestBitSet(t *testing.T) {
b8 := uint8(0)
b16 := uint16(0)
b32 := uint32(0)
b64 := uint64(0)
b := uint(0)
BitSet(&b8, 0, true)
if b8 != 1 {
t.Errorf("expected %d got %d", 1, b8)
}
BitSet(&b16, 0, true)
if b16 != 1 {
t.Errorf("expected %d got %d", 1, b16)
}
BitSet(&b32, 0, true)
if b32 != 1 {
t.Errorf("expected %d got %d", 1, b32)
}
BitSet(&b64, 0, true)
if b64 != 1 {
t.Errorf("expected %d got %d", 1, b64)
}
BitSet(&b, 0, true)
if b != 1 {
t.Errorf("expected %d got %d", 1, b)
}
BitSet(&b8, 7, true)
if b8 != 129 {
t.Errorf("expected %d got %d", 129, b8)
}
BitSet(&b16, 15, true)
if b16 != 32769 {
t.Errorf("expected %d got %d", 32769, b16)
}
BitSet(&b32, 31, true)
if b32 != 2147483649 {
t.Errorf("expected %d got %d", 2147483649, b32)
}
BitSet(&b64, 63, true)
if b64 != 9223372036854775809 {
t.Errorf("expected %d got %d", uint64(9223372036854775809), b64)
}
BitSet(&b, 1, true)
if b != 3 {
t.Errorf("expected %d got %d", 3, b)
}
BitSet(&b8, 0, false)
if b8 != 128 {
t.Errorf("expected %d got %d", 128, b8)
}
BitSet(&b16, 0, false)
if b16 != 32768 {
t.Errorf("expected %d got %d", 32768, b16)
}
BitSet(&b32, 0, false)
if b32 != 2147483648 {
t.Errorf("expected %d got %d", 2147483648, b32)
}
BitSet(&b64, 0, false)
if b64 != 9223372036854775808 {
t.Errorf("expected %d got %d", uint64(9223372036854775809), b64)
}
BitSet(&b, 0, false)
if b != 2 {
t.Errorf("expected %d got %d", 2, b)
}
e := "e"
BitSet(&e, 0, true)
if e != "e" {
t.Errorf("expected %s got %s", "e", e)
}
b8 := uint8(0)
b16 := uint16(0)
b32 := uint32(0)
b64 := uint64(0)
b := uint(0)
BitSet(&b8, 0, true)
if b8 != 1 {
t.Errorf("expected %d got %d", 1, b8)
}
BitSet(&b16, 0, true)
if b16 != 1 {
t.Errorf("expected %d got %d", 1, b16)
}
BitSet(&b32, 0, true)
if b32 != 1 {
t.Errorf("expected %d got %d", 1, b32)
}
BitSet(&b64, 0, true)
if b64 != 1 {
t.Errorf("expected %d got %d", 1, b64)
}
BitSet(&b, 0, true)
if b != 1 {
t.Errorf("expected %d got %d", 1, b)
}
BitSet(&b8, 7, true)
if b8 != 129 {
t.Errorf("expected %d got %d", 129, b8)
}
BitSet(&b16, 15, true)
if b16 != 32769 {
t.Errorf("expected %d got %d", 32769, b16)
}
BitSet(&b32, 31, true)
if b32 != 2147483649 {
t.Errorf("expected %d got %d", 2147483649, b32)
}
BitSet(&b64, 63, true)
if b64 != 9223372036854775809 {
t.Errorf("expected %d got %d", uint64(9223372036854775809), b64)
}
BitSet(&b, 1, true)
if b != 3 {
t.Errorf("expected %d got %d", 3, b)
}
BitSet(&b8, 0, false)
if b8 != 128 {
t.Errorf("expected %d got %d", 128, b8)
}
BitSet(&b16, 0, false)
if b16 != 32768 {
t.Errorf("expected %d got %d", 32768, b16)
}
BitSet(&b32, 0, false)
if b32 != 2147483648 {
t.Errorf("expected %d got %d", 2147483648, b32)
}
BitSet(&b64, 0, false)
if b64 != 9223372036854775808 {
t.Errorf("expected %d got %d", uint64(9223372036854775809), b64)
}
BitSet(&b, 0, false)
if b != 2 {
t.Errorf("expected %d got %d", 2, b)
}
e := "e"
BitSet(&e, 0, true)
if e != "e" {
t.Errorf("expected %s got %s", "e", e)
}
}
func ExampleBitSet() {
v := 0
BitSet(&v, 1, true)
fmt.Println(v)
ui := uint8(0)
BitSet(&ui, 7, true)
fmt.Println(ui)
i := int8(0)
BitSet(&i, 7, true)
fmt.Println(i)
// Output:
// 2
// 128
// -128
v := 0
BitSet(&v, 1, true)
fmt.Println(v)
ui := uint8(0)
BitSet(&ui, 7, true)
fmt.Println(ui)
i := int8(0)
BitSet(&i, 7, true)
fmt.Println(i)
// Output:
// 2
// 128
// -128
}

View File

@ -3,5 +3,5 @@ package util
import "bytes"
func BytesCombine(pBytes ...[]byte) []byte {
return bytes.Join(pBytes, []byte(""))
return bytes.Join(pBytes, []byte(""))
}

View File

@ -1,30 +1,30 @@
package util
import (
"bytes"
"fmt"
"testing"
"bytes"
"fmt"
"testing"
)
func TestBytesCombine(t *testing.T) {
b1 := []byte{0x11, 0x22}
b2 := []byte{0x33, 0x44, 0x55}
b3 := []byte{0x66}
s := []byte{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}
b := BytesCombine(b1, b2, b3)
if !bytes.Equal(b, s) {
t.Errorf("expected %v got %v", s, b)
}
b1 := []byte{0x11, 0x22}
b2 := []byte{0x33, 0x44, 0x55}
b3 := []byte{0x66}
s := []byte{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}
b := BytesCombine(b1, b2, b3)
if !bytes.Equal(b, s) {
t.Errorf("expected %v got %v", s, b)
}
}
func ExampleBytesCombine() {
b1 := []byte{11, 22}
b2 := []byte{33, 44, 55}
b3 := []byte{66}
fmt.Println(BytesCombine(b1, b2, b3))
// Output:
// [11 22 33 44 55 66]
b1 := []byte{11, 22}
b2 := []byte{33, 44, 55}
b3 := []byte{66}
fmt.Println(BytesCombine(b1, b2, b3))
// Output:
// [11 22 33 44 55 66]
}

122
conv.go
View File

@ -3,104 +3,104 @@ package util
import "encoding/binary"
func UInt16ToBytesSlice(i uint16) []byte {
var buf = make([]byte, 2)
binary.BigEndian.PutUint16(buf, i)
return buf
var buf = make([]byte, 2)
binary.BigEndian.PutUint16(buf, i)
return buf
}
func BytesSliceToUInt16(buf []byte) uint16 {
return binary.BigEndian.Uint16(buf)
return binary.BigEndian.Uint16(buf)
}
func UInt16ToBytesArray(i uint16) [2]byte {
var buf = [2]byte{}
binary.BigEndian.PutUint16(buf[:], i)
return buf
var buf = [2]byte{}
binary.BigEndian.PutUint16(buf[:], i)
return buf
}
func BytesArrayToUInt16(buf [2]byte) uint16 {
return binary.BigEndian.Uint16(buf[:])
return binary.BigEndian.Uint16(buf[:])
}
func UInt32ToBytesSlice(i uint32) []byte {
var buf = make([]byte, 4)
binary.BigEndian.PutUint32(buf, i)
return buf
var buf = make([]byte, 4)
binary.BigEndian.PutUint32(buf, i)
return buf
}
func BytesSliceToUInt32(buf []byte) uint32 {
return binary.BigEndian.Uint32(buf)
return binary.BigEndian.Uint32(buf)
}
func UInt32ToBytesArray(i uint32) [4]byte {
var buf = [4]byte{}
binary.BigEndian.PutUint32(buf[:], i)
return buf
var buf = [4]byte{}
binary.BigEndian.PutUint32(buf[:], i)
return buf
}
func BytesArrayToUInt32(buf [4]byte) uint32 {
return binary.BigEndian.Uint32(buf[:])
return binary.BigEndian.Uint32(buf[:])
}
func UInt64ToBytesSlice(i uint64) []byte {
var buf = make([]byte, 8)
binary.BigEndian.PutUint64(buf, i)
return buf
var buf = make([]byte, 8)
binary.BigEndian.PutUint64(buf, i)
return buf
}
func BytesSliceToUInt64(buf []byte) uint64 {
return binary.BigEndian.Uint64(buf)
return binary.BigEndian.Uint64(buf)
}
func UInt64ToBytesArray(i uint64) [8]byte {
var buf = [8]byte{}
binary.BigEndian.PutUint64(buf[:], i)
return buf
var buf = [8]byte{}
binary.BigEndian.PutUint64(buf[:], i)
return buf
}
func BytesArrayToUInt64(buf [8]byte) uint64 {
return binary.BigEndian.Uint64(buf[:])
return binary.BigEndian.Uint64(buf[:])
}
func UIntToBytes(i any) []byte {
switch data := i.(type) {
case uint8:
return []byte{data}
case uint16:
return func() []byte {
d := UInt16ToBytesSlice(data)
return d[:]
}()
case uint32:
return func() []byte {
d := UInt32ToBytesSlice(data)
return d[:]
}()
case uint64:
return func() []byte {
d := UInt64ToBytesSlice(data)
return d[:]
}()
}
return nil
switch data := i.(type) {
case uint8:
return []byte{data}
case uint16:
return func() []byte {
d := UInt16ToBytesSlice(data)
return d[:]
}()
case uint32:
return func() []byte {
d := UInt32ToBytesSlice(data)
return d[:]
}()
case uint64:
return func() []byte {
d := UInt64ToBytesSlice(data)
return d[:]
}()
}
return nil
}
func BytesToUInt(buf []byte) uint64 {
switch len(buf) {
case 1:
return uint64(buf[0])
case 2:
return uint64(BytesSliceToUInt16(buf))
case 4:
return uint64(BytesSliceToUInt32(buf))
case 8:
return BytesSliceToUInt64(buf)
default:
val := uint64(0)
for _, v := range buf {
val <<= 8
val = val + uint64(v)
}
return val
}
switch len(buf) {
case 1:
return uint64(buf[0])
case 2:
return uint64(BytesSliceToUInt16(buf))
case 4:
return uint64(BytesSliceToUInt32(buf))
case 8:
return BytesSliceToUInt64(buf)
default:
val := uint64(0)
for _, v := range buf {
val <<= 8
val = val + uint64(v)
}
return val
}
}

View File

@ -1,275 +1,275 @@
package util
import (
"fmt"
"fmt"
)
func ExampleUInt16ToBytesSlice() {
val := uint16(65535)
bs := UInt16ToBytesSlice(val)
fmt.Println(bs)
val /= 2
bs = UInt16ToBytesSlice(val)
fmt.Println(bs)
val -= 1
bs = UInt16ToBytesSlice(val)
fmt.Println(bs)
// Output:
// [255 255]
// [127 255]
// [127 254]
val := uint16(65535)
bs := UInt16ToBytesSlice(val)
fmt.Println(bs)
val /= 2
bs = UInt16ToBytesSlice(val)
fmt.Println(bs)
val -= 1
bs = UInt16ToBytesSlice(val)
fmt.Println(bs)
// Output:
// [255 255]
// [127 255]
// [127 254]
}
func ExampleBytesSliceToUInt16() {
bs := []byte{255, 255}
val := BytesSliceToUInt16(bs)
fmt.Println(val)
bs = []byte{127, 255}
val = BytesSliceToUInt16(bs)
fmt.Println(val)
bs = []byte{127, 254}
val = BytesSliceToUInt16(bs)
fmt.Println(val)
// Output:
// 65535
// 32767
// 32766
bs := []byte{255, 255}
val := BytesSliceToUInt16(bs)
fmt.Println(val)
bs = []byte{127, 255}
val = BytesSliceToUInt16(bs)
fmt.Println(val)
bs = []byte{127, 254}
val = BytesSliceToUInt16(bs)
fmt.Println(val)
// Output:
// 65535
// 32767
// 32766
}
func ExampleUInt16ToBytesArray() {
val := uint16(65535)
bs := UInt16ToBytesArray(val)
fmt.Println(bs)
val /= 2
bs = UInt16ToBytesArray(val)
fmt.Println(bs)
val -= 1
bs = UInt16ToBytesArray(val)
fmt.Println(bs)
// Output:
// [255 255]
// [127 255]
// [127 254]
val := uint16(65535)
bs := UInt16ToBytesArray(val)
fmt.Println(bs)
val /= 2
bs = UInt16ToBytesArray(val)
fmt.Println(bs)
val -= 1
bs = UInt16ToBytesArray(val)
fmt.Println(bs)
// Output:
// [255 255]
// [127 255]
// [127 254]
}
func ExampleBytesArrayToUInt16() {
bs := [2]byte{255, 255}
val := BytesArrayToUInt16(bs)
fmt.Println(val)
bs = [2]byte{127, 255}
val = BytesArrayToUInt16(bs)
fmt.Println(val)
bs = [2]byte{127, 254}
val = BytesArrayToUInt16(bs)
fmt.Println(val)
// Output:
// 65535
// 32767
// 32766
bs := [2]byte{255, 255}
val := BytesArrayToUInt16(bs)
fmt.Println(val)
bs = [2]byte{127, 255}
val = BytesArrayToUInt16(bs)
fmt.Println(val)
bs = [2]byte{127, 254}
val = BytesArrayToUInt16(bs)
fmt.Println(val)
// Output:
// 65535
// 32767
// 32766
}
func ExampleUInt32ToBytesSlice() {
val := uint32(4294967295)
bs := UInt32ToBytesSlice(val)
fmt.Println(bs)
val = uint32(2147483647)
bs = UInt32ToBytesSlice(val)
fmt.Println(bs)
val = uint32(2147417854)
bs = UInt32ToBytesSlice(val)
fmt.Println(bs)
// Output:
// [255 255 255 255]
// [127 255 255 255]
// [127 254 254 254]
val := uint32(4294967295)
bs := UInt32ToBytesSlice(val)
fmt.Println(bs)
val = uint32(2147483647)
bs = UInt32ToBytesSlice(val)
fmt.Println(bs)
val = uint32(2147417854)
bs = UInt32ToBytesSlice(val)
fmt.Println(bs)
// Output:
// [255 255 255 255]
// [127 255 255 255]
// [127 254 254 254]
}
func ExampleBytesSliceToUInt32() {
bs := []byte{255, 255, 255, 255}
val := BytesSliceToUInt32(bs)
fmt.Println(val)
bs = []byte{127, 255, 255, 255}
val = BytesSliceToUInt32(bs)
fmt.Println(val)
bs = []byte{127, 254, 254, 254}
val = BytesSliceToUInt32(bs)
fmt.Println(val)
// Output:
// 4294967295
// 2147483647
// 2147417854
bs := []byte{255, 255, 255, 255}
val := BytesSliceToUInt32(bs)
fmt.Println(val)
bs = []byte{127, 255, 255, 255}
val = BytesSliceToUInt32(bs)
fmt.Println(val)
bs = []byte{127, 254, 254, 254}
val = BytesSliceToUInt32(bs)
fmt.Println(val)
// Output:
// 4294967295
// 2147483647
// 2147417854
}
func ExampleUInt32ToBytesArray() {
val := uint32(4294967295)
bs := UInt32ToBytesArray(val)
fmt.Println(bs)
val = uint32(2147483647)
bs = UInt32ToBytesArray(val)
fmt.Println(bs)
val = uint32(2147417854)
bs = UInt32ToBytesArray(val)
fmt.Println(bs)
// Output:
// [255 255 255 255]
// [127 255 255 255]
// [127 254 254 254]
val := uint32(4294967295)
bs := UInt32ToBytesArray(val)
fmt.Println(bs)
val = uint32(2147483647)
bs = UInt32ToBytesArray(val)
fmt.Println(bs)
val = uint32(2147417854)
bs = UInt32ToBytesArray(val)
fmt.Println(bs)
// Output:
// [255 255 255 255]
// [127 255 255 255]
// [127 254 254 254]
}
func ExampleBytesArrayToUInt32() {
bs := [4]byte{255, 255, 255, 255}
val := BytesArrayToUInt32(bs)
fmt.Println(val)
bs = [4]byte{127, 255, 255, 255}
val = BytesArrayToUInt32(bs)
fmt.Println(val)
bs = [4]byte{127, 254, 254, 254}
val = BytesArrayToUInt32(bs)
fmt.Println(val)
// Output:
// 4294967295
// 2147483647
// 2147417854
bs := [4]byte{255, 255, 255, 255}
val := BytesArrayToUInt32(bs)
fmt.Println(val)
bs = [4]byte{127, 255, 255, 255}
val = BytesArrayToUInt32(bs)
fmt.Println(val)
bs = [4]byte{127, 254, 254, 254}
val = BytesArrayToUInt32(bs)
fmt.Println(val)
// Output:
// 4294967295
// 2147483647
// 2147417854
}
func ExampleUInt64ToBytesSlice() {
val := uint64(18446744073709551615)
bs := UInt64ToBytesSlice(val)
fmt.Println(bs)
val = uint64(9223372036854775807)
bs = UInt64ToBytesSlice(val)
fmt.Println(bs)
val = uint64(9223089458054627070)
bs = UInt64ToBytesSlice(val)
fmt.Println(bs)
// Output:
// [255 255 255 255 255 255 255 255]
// [127 255 255 255 255 255 255 255]
// [127 254 254 254 254 254 254 254]
val := uint64(18446744073709551615)
bs := UInt64ToBytesSlice(val)
fmt.Println(bs)
val = uint64(9223372036854775807)
bs = UInt64ToBytesSlice(val)
fmt.Println(bs)
val = uint64(9223089458054627070)
bs = UInt64ToBytesSlice(val)
fmt.Println(bs)
// Output:
// [255 255 255 255 255 255 255 255]
// [127 255 255 255 255 255 255 255]
// [127 254 254 254 254 254 254 254]
}
func ExampleBytesSliceToUInt64() {
bs := []byte{255, 255, 255, 255, 255, 255, 255, 255}
val := BytesSliceToUInt64(bs)
fmt.Println(val)
bs = []byte{127, 255, 255, 255, 255, 255, 255, 255}
val = BytesSliceToUInt64(bs)
fmt.Println(val)
bs = []byte{127, 254, 254, 254, 254, 254, 254, 254}
val = BytesSliceToUInt64(bs)
fmt.Println(val)
// Output:
// 18446744073709551615
// 9223372036854775807
// 9223089458054627070
bs := []byte{255, 255, 255, 255, 255, 255, 255, 255}
val := BytesSliceToUInt64(bs)
fmt.Println(val)
bs = []byte{127, 255, 255, 255, 255, 255, 255, 255}
val = BytesSliceToUInt64(bs)
fmt.Println(val)
bs = []byte{127, 254, 254, 254, 254, 254, 254, 254}
val = BytesSliceToUInt64(bs)
fmt.Println(val)
// Output:
// 18446744073709551615
// 9223372036854775807
// 9223089458054627070
}
func ExampleUInt64ToBytesArray() {
val := uint64(18446744073709551615)
bs := UInt64ToBytesArray(val)
fmt.Println(bs)
val = uint64(9223372036854775807)
bs = UInt64ToBytesArray(val)
fmt.Println(bs)
val = uint64(9223089458054627070)
bs = UInt64ToBytesArray(val)
fmt.Println(bs)
// Output:
// [255 255 255 255 255 255 255 255]
// [127 255 255 255 255 255 255 255]
// [127 254 254 254 254 254 254 254]
val := uint64(18446744073709551615)
bs := UInt64ToBytesArray(val)
fmt.Println(bs)
val = uint64(9223372036854775807)
bs = UInt64ToBytesArray(val)
fmt.Println(bs)
val = uint64(9223089458054627070)
bs = UInt64ToBytesArray(val)
fmt.Println(bs)
// Output:
// [255 255 255 255 255 255 255 255]
// [127 255 255 255 255 255 255 255]
// [127 254 254 254 254 254 254 254]
}
func ExampleBytesArrayToUInt64() {
bs := [8]byte{255, 255, 255, 255, 255, 255, 255, 255}
val := BytesArrayToUInt64(bs)
fmt.Println(val)
bs = [8]byte{127, 255, 255, 255, 255, 255, 255, 255}
val = BytesArrayToUInt64(bs)
fmt.Println(val)
bs = [8]byte{127, 254, 254, 254, 254, 254, 254, 254}
val = BytesArrayToUInt64(bs)
fmt.Println(val)
// Output:
// 18446744073709551615
// 9223372036854775807
// 9223089458054627070
bs := [8]byte{255, 255, 255, 255, 255, 255, 255, 255}
val := BytesArrayToUInt64(bs)
fmt.Println(val)
bs = [8]byte{127, 255, 255, 255, 255, 255, 255, 255}
val = BytesArrayToUInt64(bs)
fmt.Println(val)
bs = [8]byte{127, 254, 254, 254, 254, 254, 254, 254}
val = BytesArrayToUInt64(bs)
fmt.Println(val)
// Output:
// 18446744073709551615
// 9223372036854775807
// 9223089458054627070
}
func ExampleUIntToBytes() {
val8 := uint8(254)
bs := UIntToBytes(val8)
fmt.Println(bs)
val16 := uint16(65534)
bs = UIntToBytes(val16)
fmt.Println(bs)
val32 := uint32(4294967294)
bs = UIntToBytes(val32)
fmt.Println(bs)
val64 := uint64(18446744073709551614)
bs = UIntToBytes(val64)
fmt.Println(bs)
valErr := ""
bs = UIntToBytes(valErr)
fmt.Println(bs)
// Output:
// [254]
// [255 254]
// [255 255 255 254]
// [255 255 255 255 255 255 255 254]
// []
val8 := uint8(254)
bs := UIntToBytes(val8)
fmt.Println(bs)
val16 := uint16(65534)
bs = UIntToBytes(val16)
fmt.Println(bs)
val32 := uint32(4294967294)
bs = UIntToBytes(val32)
fmt.Println(bs)
val64 := uint64(18446744073709551614)
bs = UIntToBytes(val64)
fmt.Println(bs)
valErr := ""
bs = UIntToBytes(valErr)
fmt.Println(bs)
// Output:
// [254]
// [255 254]
// [255 255 255 254]
// [255 255 255 255 255 255 255 254]
// []
}
func ExampleBytesToUInt() {
bs := []byte{255}
fmt.Println(BytesToUInt(bs))
bs = []byte{255, 255}
fmt.Println(BytesToUInt(bs))
bs = []byte{255, 255, 255, 255}
fmt.Println(BytesToUInt(bs))
bs = []byte{255, 255, 255, 255, 255, 255, 255, 255}
fmt.Println(BytesToUInt(bs))
bs = []byte{255, 255, 255, 255, 255, 255, 255}
fmt.Println(BytesToUInt(bs))
// Output:
// 255
// 65535
// 4294967295
// 18446744073709551615
// 72057594037927935
bs := []byte{255}
fmt.Println(BytesToUInt(bs))
bs = []byte{255, 255}
fmt.Println(BytesToUInt(bs))
bs = []byte{255, 255, 255, 255}
fmt.Println(BytesToUInt(bs))
bs = []byte{255, 255, 255, 255, 255, 255, 255, 255}
fmt.Println(BytesToUInt(bs))
bs = []byte{255, 255, 255, 255, 255, 255, 255}
fmt.Println(BytesToUInt(bs))
// Output:
// 255
// 65535
// 4294967295
// 18446744073709551615
// 72057594037927935
}

126
crc32.go
View File

@ -1,132 +1,132 @@
package util
import (
"encoding/hex"
"hash/crc32"
"io"
"os"
"path/filepath"
"strings"
"encoding/hex"
"hash/crc32"
"io"
"os"
"path/filepath"
"strings"
)
type CRC32Result struct {
value uint32
err error
value uint32
err error
}
func (c *CRC32Result) Value() uint32 {
return c.value
return c.value
}
func (c *CRC32Result) Array() [4]byte {
return UInt32ToBytesArray(c.value)
return UInt32ToBytesArray(c.value)
}
func (c *CRC32Result) Slice() []byte {
return UInt32ToBytesSlice(c.value)
return UInt32ToBytesSlice(c.value)
}
func (c *CRC32Result) Upper() string {
return strings.ToUpper(hex.EncodeToString(c.Slice()))
return strings.ToUpper(hex.EncodeToString(c.Slice()))
}
func (c *CRC32Result) Lower() string {
return strings.ToLower(hex.EncodeToString(c.Slice()))
return strings.ToLower(hex.EncodeToString(c.Slice()))
}
func (c *CRC32Result) Error() error {
return c.err
return c.err
}
func NewCRC32Result(result uint32, err error) *CRC32Result {
return &CRC32Result{
value: result,
err: err,
}
return &CRC32Result{
value: result,
err: err,
}
}
type CRC32 struct{}
func NewCRC32() *CRC32 {
return &CRC32{}
return &CRC32{}
}
func (c *CRC32) FromReader(r io.Reader) *CRC32Result {
return c.FromReaderChunk(r, 1024*8)
return c.FromReaderChunk(r, 1024*8)
}
func (c *CRC32) FromFile(filename string) *CRC32Result {
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewCRC32Result(0, err)
}
defer func() {
_ = file.Close()
}()
return c.FromReader(file)
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewCRC32Result(0, err)
}
defer func() {
_ = file.Close()
}()
return c.FromReader(file)
}
func (c *CRC32) FromReaderChunk(r io.Reader, chunksize int) *CRC32Result {
val := uint32(0)
buf := make([]byte, chunksize)
var n int
var err error
for {
n, err = r.Read(buf)
if err != nil {
if err != io.EOF {
return NewCRC32Result(0, err)
}
if n > 0 {
val = crc32.Update(val, crc32.IEEETable, buf[:n])
}
break
}
val = crc32.Update(val, crc32.IEEETable, buf[:n])
}
return NewCRC32Result(val, nil)
val := uint32(0)
buf := make([]byte, chunksize)
var n int
var err error
for {
n, err = r.Read(buf)
if err != nil {
if err != io.EOF {
return NewCRC32Result(0, err)
}
if n > 0 {
val = crc32.Update(val, crc32.IEEETable, buf[:n])
}
break
}
val = crc32.Update(val, crc32.IEEETable, buf[:n])
}
return NewCRC32Result(val, nil)
}
func (c *CRC32) FromFileChunk(filename string, chunksize int) *CRC32Result {
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewCRC32Result(0, err)
}
defer func() {
_ = file.Close()
}()
return c.FromReaderChunk(file, chunksize)
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewCRC32Result(0, err)
}
defer func() {
_ = file.Close()
}()
return c.FromReaderChunk(file, chunksize)
}
func (c *CRC32) FromBytes(data []byte) *CRC32Result {
return NewCRC32Result(crc32.ChecksumIEEE(data), nil)
return NewCRC32Result(crc32.ChecksumIEEE(data), nil)
}
func (c *CRC32) FromString(data string) *CRC32Result {
return NewCRC32Result(crc32.ChecksumIEEE([]byte(data)), nil)
return NewCRC32Result(crc32.ChecksumIEEE([]byte(data)), nil)
}
type CRC32Pip struct {
crc uint32
crc uint32
}
func NewCRC32Pip() *CRC32Pip {
return &CRC32Pip{crc: 0}
return &CRC32Pip{crc: 0}
}
func (c *CRC32Pip) Write(data []byte) (n int, err error) {
c.crc = crc32.Update(c.crc, crc32.IEEETable, data)
return len(data), nil
c.crc = crc32.Update(c.crc, crc32.IEEETable, data)
return len(data), nil
}
func (c *CRC32Pip) WriteBytes(data []byte) {
c.crc = crc32.Update(c.crc, crc32.IEEETable, data)
c.crc = crc32.Update(c.crc, crc32.IEEETable, data)
}
func (c *CRC32Pip) WriteString(data string) {
c.crc = crc32.Update(c.crc, crc32.IEEETable, []byte(data))
c.crc = crc32.Update(c.crc, crc32.IEEETable, []byte(data))
}
func (c *CRC32Pip) Result() *CRC32Result {
return NewCRC32Result(c.crc, nil)
return NewCRC32Result(c.crc, nil)
}

View File

@ -1,169 +1,169 @@
package util
import (
"bytes"
"encoding/hex"
"fmt"
"io"
"strings"
"testing"
"bytes"
"encoding/hex"
"fmt"
"io"
"strings"
"testing"
)
func TestCRC32(t *testing.T) {
// dd if=/dev/zero of=testfile/testFile1 bs=4KB count=4
// crc32 testFile1
const fileCRC32 = "577ce78d"
fileCRC32Bytes, err := hex.DecodeString(fileCRC32)
if err != nil {
t.Errorf("fileCRC32Bytes: %v", err)
}
testString := "Akvicor"
testBytes := []byte(testString)
testStringP1 := "Akv"
testStringP2 := "icor"
testBytesP1 := []byte(testStringP1)
testBytesP2 := []byte(testStringP2)
testCRC32 := "3b60e1cd"
testCRC32P1 := "b1765880"
// test FromFile & CRC32Result
crc := NewCRC32().FromFile("testfile/testFile1")
if crc.Error() != nil {
t.Errorf("FromFile failed: %v", crc.Error())
}
if crc.Value() != BytesSliceToUInt32(fileCRC32Bytes) {
t.Errorf("FromFile failed: expected: [%d] got [%d]", BytesSliceToUInt32(fileCRC32Bytes), crc.Value())
}
if crc.Lower() != fileCRC32 {
t.Errorf("FromFile failed: expected: [%s] got [%s]", fileCRC32, crc.Lower())
}
if crc.Upper() != strings.ToUpper(fileCRC32) {
t.Errorf("FromFile failed: expected: [%s] got [%s]", strings.ToUpper(fileCRC32), crc.Upper())
}
if !bytes.Equal(crc.Slice(), fileCRC32Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileCRC32Bytes, crc.Slice())
}
ay := crc.Array()
if !bytes.Equal(ay[:], fileCRC32Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileCRC32Bytes, ay)
}
// test FromFileChunk
crc = NewCRC32().FromFileChunk("testfile/testFile1", 1024*64)
if crc.Error() != nil {
t.Errorf("FromFileChunk failed: %v", crc.Error())
}
if crc.Lower() != fileCRC32 {
t.Errorf("FromFileChunk failed: expected: [%s] got [%s]", fileCRC32, crc.Lower())
}
// test FromBytes
crc = NewCRC32().FromBytes(testBytes)
if crc.Error() != nil {
t.Errorf("FromBytes failed: %v", crc.Error())
}
if crc.Lower() != testCRC32 {
t.Errorf("FromBytes failed: expected: [%s] got [%s]", testCRC32, crc.Lower())
}
// test FromString
crc = NewCRC32().FromString(testString)
if crc.Error() != nil {
t.Errorf("FromString failed: %v", crc.Error())
}
if crc.Lower() != testCRC32 {
t.Errorf("FromString failed: expected: [%s] got [%s]", testCRC32, crc.Lower())
}
// test NewCRC32Pip.Write
cp := NewCRC32Pip()
n, err := cp.Write(testBytesP1)
if n != len(testBytesP1) || err != nil {
t.Errorf("NewCRC32Pip Write failed: [%d][%d] %v", n, len(testBytesP1), err)
}
n, err = cp.Write(testBytesP2)
if n != len(testBytesP2) || err != nil {
t.Errorf("NewCRC32Pip Write failed: [%d][%d] %v", n, len(testBytesP2), err)
}
crc = cp.Result()
if crc.Error() != nil {
t.Errorf("NewCRC32Pip Write failed: %v", crc.Error())
}
if crc.Lower() != testCRC32 {
t.Errorf("NewCRC32Pip Write failed: expected: [%s] got [%s]", testCRC32, crc.Lower())
}
// test NewCRC32Pip.WriteBytes
cp = NewCRC32Pip()
cp.WriteBytes(testBytesP1)
cp.WriteBytes(testBytesP2)
crc = cp.Result()
if crc.Error() != nil {
t.Errorf("NewCRC32Pip WriteBytes failed: %v", crc.Error())
}
if crc.Lower() != testCRC32 {
t.Errorf("NewCRC32Pip WriteBytes failed: expected: [%s] got [%s]", testCRC32, crc.Lower())
}
// test NewCRC32Pip.WriteString
cp = NewCRC32Pip()
cp.WriteString(testStringP1)
cp.WriteString(testStringP2)
crc = cp.Result()
if crc.Error() != nil {
t.Errorf("NewCRC32Pip WriteString failed: %v", crc.Error())
}
if crc.Lower() != testCRC32 {
t.Errorf("NewCRC32Pip WriteString failed: expected: [%s] got [%s]", testCRC32, crc.Lower())
}
// test NewCRC32Pip.Result
cp = NewCRC32Pip()
cp.WriteString(testStringP1)
crc = cp.Result()
if crc.Error() != nil {
t.Errorf("NewCRC32Pip WriteString failed: %v", crc.Error())
}
if crc.Lower() != testCRC32P1 {
t.Errorf("NewCRC32Pip WriteString failed: expected: [%s] got [%s]", testCRC32P1, crc.Lower())
}
cp.WriteString(testStringP2)
crc = cp.Result()
if crc.Error() != nil {
t.Errorf("NewCRC32Pip WriteString failed: %v", crc.Error())
}
if crc.Lower() != testCRC32 {
t.Errorf("NewCRC32Pip WriteString failed: expected: [%s] got [%s]", testCRC32, crc.Lower())
}
// dd if=/dev/zero of=testfile/testFile1 bs=4KB count=4
// crc32 testFile1
const fileCRC32 = "577ce78d"
fileCRC32Bytes, err := hex.DecodeString(fileCRC32)
if err != nil {
t.Errorf("fileCRC32Bytes: %v", err)
}
testString := "Akvicor"
testBytes := []byte(testString)
testStringP1 := "Akv"
testStringP2 := "icor"
testBytesP1 := []byte(testStringP1)
testBytesP2 := []byte(testStringP2)
testCRC32 := "3b60e1cd"
testCRC32P1 := "b1765880"
// test FromFile & CRC32Result
crc := NewCRC32().FromFile("testfile/testFile1")
if crc.Error() != nil {
t.Errorf("FromFile failed: %v", crc.Error())
}
if crc.Value() != BytesSliceToUInt32(fileCRC32Bytes) {
t.Errorf("FromFile failed: expected: [%d] got [%d]", BytesSliceToUInt32(fileCRC32Bytes), crc.Value())
}
if crc.Lower() != fileCRC32 {
t.Errorf("FromFile failed: expected: [%s] got [%s]", fileCRC32, crc.Lower())
}
if crc.Upper() != strings.ToUpper(fileCRC32) {
t.Errorf("FromFile failed: expected: [%s] got [%s]", strings.ToUpper(fileCRC32), crc.Upper())
}
if !bytes.Equal(crc.Slice(), fileCRC32Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileCRC32Bytes, crc.Slice())
}
ay := crc.Array()
if !bytes.Equal(ay[:], fileCRC32Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileCRC32Bytes, ay)
}
// test FromFileChunk
crc = NewCRC32().FromFileChunk("testfile/testFile1", 1024*64)
if crc.Error() != nil {
t.Errorf("FromFileChunk failed: %v", crc.Error())
}
if crc.Lower() != fileCRC32 {
t.Errorf("FromFileChunk failed: expected: [%s] got [%s]", fileCRC32, crc.Lower())
}
// test FromBytes
crc = NewCRC32().FromBytes(testBytes)
if crc.Error() != nil {
t.Errorf("FromBytes failed: %v", crc.Error())
}
if crc.Lower() != testCRC32 {
t.Errorf("FromBytes failed: expected: [%s] got [%s]", testCRC32, crc.Lower())
}
// test FromString
crc = NewCRC32().FromString(testString)
if crc.Error() != nil {
t.Errorf("FromString failed: %v", crc.Error())
}
if crc.Lower() != testCRC32 {
t.Errorf("FromString failed: expected: [%s] got [%s]", testCRC32, crc.Lower())
}
// test NewCRC32Pip.Write
cp := NewCRC32Pip()
n, err := cp.Write(testBytesP1)
if n != len(testBytesP1) || err != nil {
t.Errorf("NewCRC32Pip Write failed: [%d][%d] %v", n, len(testBytesP1), err)
}
n, err = cp.Write(testBytesP2)
if n != len(testBytesP2) || err != nil {
t.Errorf("NewCRC32Pip Write failed: [%d][%d] %v", n, len(testBytesP2), err)
}
crc = cp.Result()
if crc.Error() != nil {
t.Errorf("NewCRC32Pip Write failed: %v", crc.Error())
}
if crc.Lower() != testCRC32 {
t.Errorf("NewCRC32Pip Write failed: expected: [%s] got [%s]", testCRC32, crc.Lower())
}
// test NewCRC32Pip.WriteBytes
cp = NewCRC32Pip()
cp.WriteBytes(testBytesP1)
cp.WriteBytes(testBytesP2)
crc = cp.Result()
if crc.Error() != nil {
t.Errorf("NewCRC32Pip WriteBytes failed: %v", crc.Error())
}
if crc.Lower() != testCRC32 {
t.Errorf("NewCRC32Pip WriteBytes failed: expected: [%s] got [%s]", testCRC32, crc.Lower())
}
// test NewCRC32Pip.WriteString
cp = NewCRC32Pip()
cp.WriteString(testStringP1)
cp.WriteString(testStringP2)
crc = cp.Result()
if crc.Error() != nil {
t.Errorf("NewCRC32Pip WriteString failed: %v", crc.Error())
}
if crc.Lower() != testCRC32 {
t.Errorf("NewCRC32Pip WriteString failed: expected: [%s] got [%s]", testCRC32, crc.Lower())
}
// test NewCRC32Pip.Result
cp = NewCRC32Pip()
cp.WriteString(testStringP1)
crc = cp.Result()
if crc.Error() != nil {
t.Errorf("NewCRC32Pip WriteString failed: %v", crc.Error())
}
if crc.Lower() != testCRC32P1 {
t.Errorf("NewCRC32Pip WriteString failed: expected: [%s] got [%s]", testCRC32P1, crc.Lower())
}
cp.WriteString(testStringP2)
crc = cp.Result()
if crc.Error() != nil {
t.Errorf("NewCRC32Pip WriteString failed: %v", crc.Error())
}
if crc.Lower() != testCRC32 {
t.Errorf("NewCRC32Pip WriteString failed: expected: [%s] got [%s]", testCRC32, crc.Lower())
}
}
func ExampleNewCRC32() {
crc := NewCRC32()
res := crc.FromString("Akvicor")
if res.Error() == nil {
fmt.Println(res.Value())
fmt.Println(res.Lower())
fmt.Println(res.Upper())
}
// Output:
// 996205005
// 3b60e1cd
// 3B60E1CD
crc := NewCRC32()
res := crc.FromString("Akvicor")
if res.Error() == nil {
fmt.Println(res.Value())
fmt.Println(res.Lower())
fmt.Println(res.Upper())
}
// Output:
// 996205005
// 3b60e1cd
// 3B60E1CD
}
func ExampleNewCRC32Pip() {
cp := NewCRC32Pip()
_, err := io.WriteString(cp, "Akvicor")
if err != nil {
fmt.Println(err)
}
res := cp.Result()
if res.Error() == nil {
fmt.Println(res.Array())
fmt.Println(res.Slice())
}
// Output:
// [59 96 225 205]
// [59 96 225 205]
cp := NewCRC32Pip()
_, err := io.WriteString(cp, "Akvicor")
if err != nil {
fmt.Println(err)
}
res := cp.Result()
if res.Error() == nil {
fmt.Println(res.Array())
fmt.Println(res.Slice())
}
// Output:
// [59 96 225 205]
// [59 96 225 205]
}

28
file.go
View File

@ -1,24 +1,24 @@
package util
import (
"os"
"path/filepath"
"os"
"path/filepath"
)
const (
FileStatNotExist = 0
FileStatIsDir = 1
FileStatIsFile = 2
FileStatNotExist = 0
FileStatIsDir = 1
FileStatIsFile = 2
)
func FileStat(filename string) int {
info, err := os.Stat(filepath.Clean(filename))
if os.IsNotExist(err) {
return FileStatNotExist
}
if info.IsDir() {
return FileStatIsDir
} else {
return FileStatIsFile
}
info, err := os.Stat(filepath.Clean(filename))
if os.IsNotExist(err) {
return FileStatNotExist
}
if info.IsDir() {
return FileStatIsDir
} else {
return FileStatIsFile
}
}

View File

@ -1,36 +1,36 @@
package util
import (
"fmt"
"testing"
"fmt"
"testing"
)
func TestFileStat(t *testing.T) {
// dd if=/dev/zero of=testfile/testFile1 bs=4KB count=4
if FileStat("testfile") != FileStatIsDir {
t.Errorf("FileStatIsDir")
}
if FileStat("testfile/testFile1") != FileStatIsFile {
t.Errorf("FileStatIsFile")
}
if FileStat("testfile/testFile2") != FileStatNotExist {
t.Errorf("FileStatNotExist")
}
// dd if=/dev/zero of=testfile/testFile1 bs=4KB count=4
if FileStat("testfile") != FileStatIsDir {
t.Errorf("FileStatIsDir")
}
if FileStat("testfile/testFile1") != FileStatIsFile {
t.Errorf("FileStatIsFile")
}
if FileStat("testfile/testFile2") != FileStatNotExist {
t.Errorf("FileStatNotExist")
}
}
func ExampleFileStat() {
if FileStat("testfile") == FileStatIsDir {
fmt.Println("FileStatIsDir")
}
if FileStat("testfile/testFile1") == FileStatIsFile {
fmt.Println("FileStatIsFile")
}
if FileStat("testfile/testFile2") == FileStatNotExist {
fmt.Println("FileStatNotExist")
}
if FileStat("testfile") == FileStatIsDir {
fmt.Println("FileStatIsDir")
}
if FileStat("testfile/testFile1") == FileStatIsFile {
fmt.Println("FileStatIsFile")
}
if FileStat("testfile/testFile2") == FileStatNotExist {
fmt.Println("FileStatNotExist")
}
// Output:
// FileStatIsDir
// FileStatIsFile
// FileStatNotExist
// Output:
// FileStatIsDir
// FileStatIsFile
// FileStatNotExist
}

402
http.go
View File

@ -1,269 +1,269 @@
package util
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"bytes"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
)
func RemoteIP(r *http.Request) string {
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
return ip
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
return ip
}
func GetClientIP(r *http.Request) string {
ip := strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0])
if ip != "" {
return ip
}
ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
if ip != "" {
return ip
}
if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
return ip
}
return ""
ip := strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0])
if ip != "" {
return ip
}
ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
if ip != "" {
return ip
}
if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
return ip
}
return ""
}
func GetClientPublicIP(r *http.Request) string {
var ip string
for _, ip = range strings.Split(r.Header.Get("X-Forwarded-For"), ",") {
if ip = strings.TrimSpace(ip); ip != "" && !IsLocalIPAddr(ip) {
return ip
}
}
if ip = strings.TrimSpace(r.Header.Get("X-Real-Ip")); ip != "" && !IsLocalIPAddr(ip) {
return ip
}
if ip = RemoteIP(r); !IsLocalIPAddr(ip) {
return ip
}
return ""
var ip string
for _, ip = range strings.Split(r.Header.Get("X-Forwarded-For"), ",") {
if ip = strings.TrimSpace(ip); ip != "" && !IsLocalIPAddr(ip) {
return ip
}
}
if ip = strings.TrimSpace(r.Header.Get("X-Real-Ip")); ip != "" && !IsLocalIPAddr(ip) {
return ip
}
if ip = RemoteIP(r); !IsLocalIPAddr(ip) {
return ip
}
return ""
}
func RespRedirect(w http.ResponseWriter, r *http.Request, url string) {
http.Redirect(w, r, url, http.StatusMovedPermanently)
http.Redirect(w, r, url, http.StatusMovedPermanently)
}
func LastPage(w http.ResponseWriter, r *http.Request) {
RespRedirect(w, r, r.URL.String()[:strings.LastIndexByte(r.URL.String(), '/')])
RespRedirect(w, r, r.URL.String()[:strings.LastIndexByte(r.URL.String(), '/')])
}
func Reload(w http.ResponseWriter, r *http.Request) {
RespRedirect(w, r, r.URL.String())
RespRedirect(w, r, r.URL.String())
}
// HTTPRespCode Util Reserved code range (-100,100)
type HTTPRespCode int
const (
HTTPRespCodeOKCode HTTPRespCode = 0
HTTPRespCodeOKMsg string = "ok"
HTTPRespCodeERCode HTTPRespCode = 1
HTTPRespCodeERMsg string = "failed to respond"
HTTPRespCodeInvalidKeyCode HTTPRespCode = 2
HTTPRespCodeInvalidKeyMsg string = "invalid key"
HTTPRespCodeProcessingFailedCode HTTPRespCode = 3
HTTPRespCodeProcessingFailedMsg string = "processing failed"
HTTPRespCodeInvalidInputCode HTTPRespCode = 4
HTTPRespCodeInvalidInputMsg string = "invalid input"
HTTPRespCodeOKCode HTTPRespCode = 0
HTTPRespCodeOKMsg string = "ok"
HTTPRespCodeERCode HTTPRespCode = 1
HTTPRespCodeERMsg string = "failed to respond"
HTTPRespCodeInvalidKeyCode HTTPRespCode = 2
HTTPRespCodeInvalidKeyMsg string = "invalid key"
HTTPRespCodeProcessingFailedCode HTTPRespCode = 3
HTTPRespCodeProcessingFailedMsg string = "processing failed"
HTTPRespCodeInvalidInputCode HTTPRespCode = 4
HTTPRespCodeInvalidInputMsg string = "invalid input"
)
type HTTPRespAPIModel struct {
Code HTTPRespCode `json:"code"`
Msg string `json:"msg"`
Code HTTPRespCode `json:"code"`
Msg string `json:"msg"`
}
func (r *HTTPRespAPIModel) String() string {
data, err := json.Marshal(r)
if err != nil {
return fmt.Sprintf(`{"code":%d,"msg":"%s"}`, HTTPRespCodeERCode, HTTPRespCodeERMsg)
}
return string(data)
data, err := json.Marshal(r)
if err != nil {
return fmt.Sprintf(`{"code":%d,"msg":"%s"}`, HTTPRespCodeERCode, HTTPRespCodeERMsg)
}
return string(data)
}
// NewHTTPResp Util Reserved code range (-100,100)
func NewHTTPResp(code HTTPRespCode, msg string) *HTTPRespAPIModel {
return &HTTPRespAPIModel{
Code: code,
Msg: msg,
}
return &HTTPRespAPIModel{
Code: code,
Msg: msg,
}
}
func ParseHTTPResp(respstr string) *HTTPRespAPIModel {
resp := &HTTPRespAPIModel{}
err := json.Unmarshal([]byte(respstr), resp)
if err != nil {
return nil
}
return resp
resp := &HTTPRespAPIModel{}
err := json.Unmarshal([]byte(respstr), resp)
if err != nil {
return nil
}
return resp
}
func WriteHTTPRespAPIOk(w http.ResponseWriter, msg ...any) {
m := HTTPRespCodeOKMsg
if len(msg) > 0 {
m = fmt.Sprint(msg...)
}
_, _ = w.Write([]byte(NewHTTPResp(HTTPRespCodeOKCode, m).String()))
m := HTTPRespCodeOKMsg
if len(msg) > 0 {
m = fmt.Sprint(msg...)
}
_, _ = w.Write([]byte(NewHTTPResp(HTTPRespCodeOKCode, m).String()))
}
func WriteHTTPRespAPIFailed(w http.ResponseWriter, msg ...any) {
m := HTTPRespCodeERMsg
if len(msg) > 0 {
m = fmt.Sprint(msg...)
}
_, _ = w.Write([]byte(NewHTTPResp(HTTPRespCodeERCode, m).String()))
m := HTTPRespCodeERMsg
if len(msg) > 0 {
m = fmt.Sprint(msg...)
}
_, _ = w.Write([]byte(NewHTTPResp(HTTPRespCodeERCode, m).String()))
}
func WriteHTTPRespAPIInvalidKey(w http.ResponseWriter, msg ...any) {
m := HTTPRespCodeInvalidKeyMsg
if len(msg) > 0 {
m = fmt.Sprint(msg...)
}
_, _ = w.Write([]byte(NewHTTPResp(HTTPRespCodeInvalidKeyCode, m).String()))
m := HTTPRespCodeInvalidKeyMsg
if len(msg) > 0 {
m = fmt.Sprint(msg...)
}
_, _ = w.Write([]byte(NewHTTPResp(HTTPRespCodeInvalidKeyCode, m).String()))
}
func WriteHTTPRespAPIInvalidInput(w http.ResponseWriter, msg ...any) {
m := HTTPRespCodeInvalidInputMsg
if len(msg) > 0 {
m = fmt.Sprint(msg...)
}
_, _ = w.Write([]byte(NewHTTPResp(HTTPRespCodeInvalidInputCode, m).String()))
m := HTTPRespCodeInvalidInputMsg
if len(msg) > 0 {
m = fmt.Sprint(msg...)
}
_, _ = w.Write([]byte(NewHTTPResp(HTTPRespCodeInvalidInputCode, m).String()))
}
func WriteHTTPRespAPIProcessingFailed(w http.ResponseWriter, msg ...any) {
m := HTTPRespCodeProcessingFailedMsg
if len(msg) > 0 {
m = fmt.Sprint(msg...)
}
_, _ = w.Write([]byte(NewHTTPResp(HTTPRespCodeProcessingFailedCode, m).String()))
m := HTTPRespCodeProcessingFailedMsg
if len(msg) > 0 {
m = fmt.Sprint(msg...)
}
_, _ = w.Write([]byte(NewHTTPResp(HTTPRespCodeProcessingFailedCode, m).String()))
}
const (
HTTPContentTypeUrlencoded = "application/x-www-form-urlencoded; charset=utf-8"
HTTPContentTypeJson = "application/json; charset=UTF-8"
// HTTPContentTypePlain = "text/plain; charset=utf-8"
// HTTPContentTypeFormData = "multipart/form-data; charset=utf-8"
HTTPContentTypeUrlencoded = "application/x-www-form-urlencoded; charset=utf-8"
HTTPContentTypeJson = "application/json; charset=UTF-8"
// HTTPContentTypePlain = "text/plain; charset=utf-8"
// HTTPContentTypeFormData = "multipart/form-data; charset=utf-8"
)
func HttpGet(u string, args any) []byte {
arg := NewJSON(args, false).Map()
req, err := http.NewRequest("GET", u, nil)
if err != nil {
return nil
}
q := req.URL.Query()
for k, v := range arg {
q.Add(k, fmt.Sprint(v))
}
req.URL.RawQuery = q.Encode()
req.Header.Add("Content-Type", HTTPContentTypeJson)
client := &http.Client{}
rsp, err := client.Do(req)
if err != nil {
return nil
}
defer rsp.Body.Close()
body, err := io.ReadAll(rsp.Body)
if err != nil {
return nil
}
return body
arg := NewJSON(args, false).Map()
req, err := http.NewRequest("GET", u, nil)
if err != nil {
return nil
}
q := req.URL.Query()
for k, v := range arg {
q.Add(k, fmt.Sprint(v))
}
req.URL.RawQuery = q.Encode()
req.Header.Add("Content-Type", HTTPContentTypeJson)
client := &http.Client{}
rsp, err := client.Do(req)
if err != nil {
return nil
}
defer rsp.Body.Close()
body, err := io.ReadAll(rsp.Body)
if err != nil {
return nil
}
return body
}
func HttpPost(contentType string, u string, args any) []byte {
var req *http.Request
var err error
if contentType == HTTPContentTypeUrlencoded {
arg := NewJSON(args, false).Map()
payload := url.Values{}
for k, v := range arg {
payload.Set(k, fmt.Sprint(v))
}
req, err = http.NewRequest("POST", u, strings.NewReader(payload.Encode()))
if err != nil {
return nil
}
} else if contentType == HTTPContentTypeJson {
req, err = http.NewRequest("POST", u, bytes.NewBuffer(NewJSON(args, false).Bytes()))
if err != nil {
return nil
}
} else {
return nil
}
req.Header.Add("Content-Type", contentType)
client := &http.Client{}
rsp, err := client.Do(req)
if err != nil {
return nil
}
defer rsp.Body.Close()
body, err := io.ReadAll(rsp.Body)
if err != nil {
return nil
}
return body
var req *http.Request
var err error
if contentType == HTTPContentTypeUrlencoded {
arg := NewJSON(args, false).Map()
payload := url.Values{}
for k, v := range arg {
payload.Set(k, fmt.Sprint(v))
}
req, err = http.NewRequest("POST", u, strings.NewReader(payload.Encode()))
if err != nil {
return nil
}
} else if contentType == HTTPContentTypeJson {
req, err = http.NewRequest("POST", u, bytes.NewBuffer(NewJSON(args, false).Bytes()))
if err != nil {
return nil
}
} else {
return nil
}
req.Header.Add("Content-Type", contentType)
client := &http.Client{}
rsp, err := client.Do(req)
if err != nil {
return nil
}
defer rsp.Body.Close()
body, err := io.ReadAll(rsp.Body)
if err != nil {
return nil
}
return body
}
func HttpPostGet(contentType string, u string, argsGET, argsPOST any) []byte {
var req *http.Request
var err error
if contentType == HTTPContentTypeUrlencoded {
arg := NewJSON(argsPOST, false).Map()
payload := url.Values{}
for k, v := range arg {
payload.Set(k, fmt.Sprint(v))
}
req, err = http.NewRequest("POST", u, strings.NewReader(payload.Encode()))
if err != nil {
return nil
}
} else if contentType == HTTPContentTypeJson {
req, err = http.NewRequest("POST", u, bytes.NewBuffer(NewJSON(argsPOST, false).Bytes()))
if err != nil {
return nil
}
} else {
return nil
}
req.Header.Add("Content-Type", contentType)
argGet := NewJSON(argsGET, false).Map()
q := req.URL.Query()
for k, v := range argGet {
q.Add(k, fmt.Sprint(v))
}
req.URL.RawQuery = q.Encode()
client := &http.Client{}
rsp, err := client.Do(req)
if err != nil {
return nil
}
defer rsp.Body.Close()
body, err := io.ReadAll(rsp.Body)
if err != nil {
return nil
}
return body
var req *http.Request
var err error
if contentType == HTTPContentTypeUrlencoded {
arg := NewJSON(argsPOST, false).Map()
payload := url.Values{}
for k, v := range arg {
payload.Set(k, fmt.Sprint(v))
}
req, err = http.NewRequest("POST", u, strings.NewReader(payload.Encode()))
if err != nil {
return nil
}
} else if contentType == HTTPContentTypeJson {
req, err = http.NewRequest("POST", u, bytes.NewBuffer(NewJSON(argsPOST, false).Bytes()))
if err != nil {
return nil
}
} else {
return nil
}
req.Header.Add("Content-Type", contentType)
argGet := NewJSON(argsGET, false).Map()
q := req.URL.Query()
for k, v := range argGet {
q.Add(k, fmt.Sprint(v))
}
req.URL.RawQuery = q.Encode()
client := &http.Client{}
rsp, err := client.Do(req)
if err != nil {
return nil
}
defer rsp.Body.Close()
body, err := io.ReadAll(rsp.Body)
if err != nil {
return nil
}
return body
}

View File

@ -1,155 +1,155 @@
package util
import (
"fmt"
"net/http"
"testing"
"fmt"
"net/http"
"testing"
)
func TestRemoteIP(t *testing.T) {
for _, v := range []struct {
remoteAddr string
expected string
}{
{"101.1.0.4:100", "101.1.0.4"},
{"101.1.0.4:", "101.1.0.4"},
{"101.1.0.4", ""},
{":100", ""},
} {
if got := RemoteIP(&http.Request{RemoteAddr: v.remoteAddr}); got != v.expected {
t.Errorf("RemoteAddr:%s expected %s, got %s", v.remoteAddr, v.expected, got)
}
}
for _, v := range []struct {
remoteAddr string
expected string
}{
{"101.1.0.4:100", "101.1.0.4"},
{"101.1.0.4:", "101.1.0.4"},
{"101.1.0.4", ""},
{":100", ""},
} {
if got := RemoteIP(&http.Request{RemoteAddr: v.remoteAddr}); got != v.expected {
t.Errorf("RemoteAddr:%s expected %s, got %s", v.remoteAddr, v.expected, got)
}
}
}
func TestGetClientIP(t *testing.T) {
r := &http.Request{Header: http.Header{}}
r.Header.Set("X-Real-IP", " 10.10.10.10 ")
r.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
r.RemoteAddr = " 40.40.40.40:42123 "
if ip := GetClientIP(r); ip != "20.20.20.20" {
t.Errorf("expected: 20.20.20.20, got: %s", ip)
}
r.Header.Del("X-Forwarded-For")
if ip := GetClientIP(r); ip != "10.10.10.10" {
t.Errorf("expected: 10.10.10.10, got: %s", ip)
}
r.Header.Set("X-Forwarded-For", "30.30.30.30 ")
if ip := GetClientIP(r); ip != "30.30.30.30" {
t.Errorf("expected: 30.30.30.30, got: %s", ip)
}
r.Header.Del("X-Forwarded-For")
r.Header.Del("X-Real-IP")
if ip := GetClientIP(r); ip != "40.40.40.40" {
t.Errorf("expected: 40.40.40.40, got: %s", ip)
}
r.RemoteAddr = "50.50.50.50"
if ip := GetClientIP(r); ip != "" {
t.Errorf("expected: 50.50.50.50, got: %s", ip)
}
r := &http.Request{Header: http.Header{}}
r.Header.Set("X-Real-IP", " 10.10.10.10 ")
r.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
r.RemoteAddr = " 40.40.40.40:42123 "
if ip := GetClientIP(r); ip != "20.20.20.20" {
t.Errorf("expected: 20.20.20.20, got: %s", ip)
}
r.Header.Del("X-Forwarded-For")
if ip := GetClientIP(r); ip != "10.10.10.10" {
t.Errorf("expected: 10.10.10.10, got: %s", ip)
}
r.Header.Set("X-Forwarded-For", "30.30.30.30 ")
if ip := GetClientIP(r); ip != "30.30.30.30" {
t.Errorf("expected: 30.30.30.30, got: %s", ip)
}
r.Header.Del("X-Forwarded-For")
r.Header.Del("X-Real-IP")
if ip := GetClientIP(r); ip != "40.40.40.40" {
t.Errorf("expected: 40.40.40.40, got: %s", ip)
}
r.RemoteAddr = "50.50.50.50"
if ip := GetClientIP(r); ip != "" {
t.Errorf("expected: 50.50.50.50, got: %s", ip)
}
}
func TestGetClientPublicIP(t *testing.T) {
for _, v := range []struct {
xForwardedFor string
remoteAddr string
expected string
}{
{"10.3.5.45, 21.45.9.1", "101.1.0.4:100", "21.45.9.1"},
{"101.3.5.45, 21.45.9.1", "101.1.0.4:100", "101.3.5.45"},
{"", "101.1.0.4:100", "101.1.0.4"},
{"21.45.9.1", "101.1.0.4:100", "21.45.9.1"},
{"21.45.9.1, ", "101.1.0.4:100", "21.45.9.1"},
{"192.168.5.45, 210.45.9.1, 89.5.6.1", "101.1.0.4:100", "210.45.9.1"},
{"192.168.5.45, 172.24.9.1, 89.5.6.1", "101.1.0.4:100", "89.5.6.1"},
{"192.168.5.45, 172.24.9.1", "101.1.0.4:100", "101.1.0.4"},
{"192.168.5.45, 172.24.9.1", "101.1.0.4:5670", "101.1.0.4"},
} {
if got := GetClientPublicIP(&http.Request{
Header: http.Header{
"X-Forwarded-For": []string{v.xForwardedFor},
},
RemoteAddr: v.remoteAddr,
}); got != v.expected {
t.Errorf("IsxForwardedFor:%s, remoteAddr:%s, client ip Should Equal %s", v.xForwardedFor, v.remoteAddr, v.expected)
}
}
r := &http.Request{Header: http.Header{}}
r.Header.Set("X-Real-IP", " 10.10.10.10 ")
r.Header.Set("X-Forwarded-For", " 172.17.40.152, 192.168.5.45")
r.RemoteAddr = "40.40.40.40:42123 "
if ip := GetClientPublicIP(r); ip != "40.40.40.40" {
t.Errorf("expected:40.40.40.40, got:%s", ip)
}
r.Header.Set("X-Real-IP", " 50.50.50.50 ")
if ip := GetClientPublicIP(r); ip != "50.50.50.50" {
t.Errorf("expected:50.50.50.50, got:%s", ip)
}
r.Header.Del("X-Real-IP")
r.Header.Del("X-Forwarded-For")
r.RemoteAddr = "127.0.0.1:42123 "
if ip := GetClientPublicIP(r); ip != "" {
t.Errorf("expected:127.0.0.1, got:%s", ip)
}
for _, v := range []struct {
xForwardedFor string
remoteAddr string
expected string
}{
{"10.3.5.45, 21.45.9.1", "101.1.0.4:100", "21.45.9.1"},
{"101.3.5.45, 21.45.9.1", "101.1.0.4:100", "101.3.5.45"},
{"", "101.1.0.4:100", "101.1.0.4"},
{"21.45.9.1", "101.1.0.4:100", "21.45.9.1"},
{"21.45.9.1, ", "101.1.0.4:100", "21.45.9.1"},
{"192.168.5.45, 210.45.9.1, 89.5.6.1", "101.1.0.4:100", "210.45.9.1"},
{"192.168.5.45, 172.24.9.1, 89.5.6.1", "101.1.0.4:100", "89.5.6.1"},
{"192.168.5.45, 172.24.9.1", "101.1.0.4:100", "101.1.0.4"},
{"192.168.5.45, 172.24.9.1", "101.1.0.4:5670", "101.1.0.4"},
} {
if got := GetClientPublicIP(&http.Request{
Header: http.Header{
"X-Forwarded-For": []string{v.xForwardedFor},
},
RemoteAddr: v.remoteAddr,
}); got != v.expected {
t.Errorf("IsxForwardedFor:%s, remoteAddr:%s, client ip Should Equal %s", v.xForwardedFor, v.remoteAddr, v.expected)
}
}
r := &http.Request{Header: http.Header{}}
r.Header.Set("X-Real-IP", " 10.10.10.10 ")
r.Header.Set("X-Forwarded-For", " 172.17.40.152, 192.168.5.45")
r.RemoteAddr = "40.40.40.40:42123 "
if ip := GetClientPublicIP(r); ip != "40.40.40.40" {
t.Errorf("expected:40.40.40.40, got:%s", ip)
}
r.Header.Set("X-Real-IP", " 50.50.50.50 ")
if ip := GetClientPublicIP(r); ip != "50.50.50.50" {
t.Errorf("expected:50.50.50.50, got:%s", ip)
}
r.Header.Del("X-Real-IP")
r.Header.Del("X-Forwarded-For")
r.RemoteAddr = "127.0.0.1:42123 "
if ip := GetClientPublicIP(r); ip != "" {
t.Errorf("expected:127.0.0.1, got:%s", ip)
}
}
func ExampleNewHTTPResp() {
fmt.Println(NewHTTPResp(HTTPRespCodeOKCode, HTTPRespCodeOKMsg))
// Output:
// {"code":0,"msg":"ok"}
fmt.Println(NewHTTPResp(HTTPRespCodeOKCode, HTTPRespCodeOKMsg))
// Output:
// {"code":0,"msg":"ok"}
}
func ExampleParseHTTPResp() {
fmt.Println(ParseHTTPResp(`{"code":0,"msg":"ok"}`).String())
// Output:
// {"code":0,"msg":"ok"}
fmt.Println(ParseHTTPResp(`{"code":0,"msg":"ok"}`).String())
// Output:
// {"code":0,"msg":"ok"}
}
func ExampleHttpGet() {
i := NewJSONResult(HttpGet("https://jsonplaceholder.typicode.com/posts/1", nil))
i1 := NewJSONResult(HttpGet("https://jsonplaceholder.typicode.com/posts", map[string]any{"id": 1}))
i2 := NewJSONResult(HttpGet("https://jsonplaceholder.typicode.com/posts", map[string]any{"id": 2}))
if fmt.Sprint(i.Map()["id"]) != "1" {
fmt.Println(i)
}
if fmt.Sprint(i1.Map()["id"]) != "1" {
fmt.Println(i1)
}
if fmt.Sprint(i2.MapArray()[0]["id"]) != "2" {
fmt.Println(i2)
}
// Output:
//
i := NewJSONResult(HttpGet("https://jsonplaceholder.typicode.com/posts/1", nil))
i1 := NewJSONResult(HttpGet("https://jsonplaceholder.typicode.com/posts", map[string]any{"id": 1}))
i2 := NewJSONResult(HttpGet("https://jsonplaceholder.typicode.com/posts", map[string]any{"id": 2}))
if fmt.Sprint(i.Map()["id"]) != "1" {
fmt.Println(i)
}
if fmt.Sprint(i1.Map()["id"]) != "1" {
fmt.Println(i1)
}
if fmt.Sprint(i2.MapArray()[0]["id"]) != "2" {
fmt.Println(i2)
}
// Output:
//
}
func ExampleHttpPost() {
i1 := NewJSONResult(HttpPost(HTTPContentTypeUrlencoded, "https://jsonplaceholder.typicode.com/posts", map[string]any{"title": "t1", "body": "b1", "userId": 1}))
if fmt.Sprint(i1.Map()["id"]) != "101" {
fmt.Println(i1)
}
// Output:
//
i1 := NewJSONResult(HttpPost(HTTPContentTypeUrlencoded, "https://jsonplaceholder.typicode.com/posts", map[string]any{"title": "t1", "body": "b1", "userId": 1}))
if fmt.Sprint(i1.Map()["id"]) != "101" {
fmt.Println(i1)
}
// Output:
//
}
func ExampleHttpPostGet() {
i1 := NewJSONResult(HttpPostGet(HTTPContentTypeUrlencoded, "https://jsonplaceholder.typicode.com/posts", map[string]any{"title": "t2", "body": "b2", "userId": 2}, map[string]any{"title": "t1", "body": "b1", "userId": 1}))
if fmt.Sprint(i1.Map()["id"]) != "101" {
fmt.Println(i1)
}
// Output:
//
i1 := NewJSONResult(HttpPostGet(HTTPContentTypeUrlencoded, "https://jsonplaceholder.typicode.com/posts", map[string]any{"title": "t2", "body": "b2", "userId": 2}, map[string]any{"title": "t1", "body": "b1", "userId": 1}))
if fmt.Sprint(i1.Map()["id"]) != "101" {
fmt.Println(i1)
}
// Output:
//
}

112
ip.go
View File

@ -1,83 +1,83 @@
package util
import (
"errors"
"net"
"errors"
"net"
)
func IsIPAddr(ip string) bool {
i := net.ParseIP(ip)
return i != nil
i := net.ParseIP(ip)
return i != nil
}
func IsLocalIPAddr(ip string) bool {
i := net.ParseIP(ip)
if i == nil {
return false
}
return IsLocalIP(i)
i := net.ParseIP(ip)
if i == nil {
return false
}
return IsLocalIP(i)
}
func IsLocalIP(ip net.IP) bool {
if ip == nil {
return false
}
if ip.IsLoopback() {
return true
}
ip4 := ip.To4()
if ip4 == nil {
return false
}
return ip4[0] == 10 || // 10.0.0.0/8
(ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31) || // 172.16.0.0/12
(ip4[0] == 169 && ip4[1] == 254) || // 169.254.0.0/16
(ip4[0] == 192 && ip4[1] == 168) // 192.168.0.0/16
if ip == nil {
return false
}
if ip.IsLoopback() {
return true
}
ip4 := ip.To4()
if ip4 == nil {
return false
}
return ip4[0] == 10 || // 10.0.0.0/8
(ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31) || // 172.16.0.0/12
(ip4[0] == 169 && ip4[1] == 254) || // 169.254.0.0/16
(ip4[0] == 192 && ip4[1] == 168) // 192.168.0.0/16
}
var ErrorInvalidIPV4Format = errors.New("invalid ipv4 format")
func IPAddrToUint32(ip string) (uint32, error) {
i := net.ParseIP(ip)
if i == nil {
return 0, ErrorInvalidIPV4Format
}
b := i.To4()
if b == nil {
return 0, ErrorInvalidIPV4Format
}
return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24, nil
i := net.ParseIP(ip)
if i == nil {
return 0, ErrorInvalidIPV4Format
}
b := i.To4()
if b == nil {
return 0, ErrorInvalidIPV4Format
}
return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24, nil
}
func Uint32ToIPAddr(i uint32) string {
ip := make(net.IP, net.IPv4len)
ip[0] = byte(i >> 24)
ip[1] = byte(i >> 16)
ip[2] = byte(i >> 8)
ip[3] = byte(i)
return ip.String()
ip := make(net.IP, net.IPv4len)
ip[0] = byte(i >> 24)
ip[1] = byte(i >> 16)
ip[2] = byte(i >> 8)
ip[3] = byte(i)
return ip.String()
}
func IPToUint32(ip net.IP) (uint32, error) {
b := ip.To4()
if b == nil {
return 0, ErrorInvalidIPV4Format
}
return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24, nil
b := ip.To4()
if b == nil {
return 0, ErrorInvalidIPV4Format
}
return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24, nil
}
func Uint32ToIP(i uint32) net.IP {
ip := make(net.IP, net.IPv4len)
ip[0] = byte(i >> 24)
ip[1] = byte(i >> 16)
ip[2] = byte(i >> 8)
ip[3] = byte(i)
return ip
ip := make(net.IP, net.IPv4len)
ip[0] = byte(i >> 24)
ip[1] = byte(i >> 16)
ip[2] = byte(i >> 8)
ip[3] = byte(i)
return ip
}

View File

@ -1,188 +1,188 @@
package util
import (
"net"
"testing"
"net"
"testing"
)
func TestIsIPAddr(t *testing.T) {
for ip, expected := range map[string]bool{
"": false,
"invalid ip address": false,
"127.0.0.1": true,
"::1": true,
"1.1.1.1": true,
} {
if IsIPAddr(ip) != expected {
t.Errorf("ip %s expected %v, got %v", ip, expected, IsIPAddr(ip))
}
}
for ip, expected := range map[string]bool{
"": false,
"invalid ip address": false,
"127.0.0.1": true,
"::1": true,
"1.1.1.1": true,
} {
if IsIPAddr(ip) != expected {
t.Errorf("ip %s expected %v, got %v", ip, expected, IsIPAddr(ip))
}
}
}
func TestIsLocalIPAddr(t *testing.T) {
for ip, expected := range map[string]bool{
"": false,
"invalid ip address": false,
"127.0.0.1": true,
"::1": true,
"182.56.9.18": false,
"192.168.9.18": true,
"10.168.9.18": true,
"11.168.9.18": false,
"172.16.9.18": true,
"172.17.9.18": true,
"172.18.9.18": true,
"172.19.9.18": true,
"172.20.9.18": true,
"172.21.9.18": true,
"172.22.9.18": true,
"172.23.9.18": true,
"172.24.9.18": true,
"172.25.9.18": true,
"172.26.9.18": true,
"172.27.9.18": true,
"172.28.9.18": true,
"172.29.9.18": true,
"172.30.9.18": true,
"172.31.9.18": true,
"172.32.9.18": false,
} {
if IsLocalIPAddr(ip) != expected {
t.Errorf("ip %s expected %v, got %v", ip, expected, IsLocalIPAddr(ip))
}
}
for ip, expected := range map[string]bool{
"": false,
"invalid ip address": false,
"127.0.0.1": true,
"::1": true,
"182.56.9.18": false,
"192.168.9.18": true,
"10.168.9.18": true,
"11.168.9.18": false,
"172.16.9.18": true,
"172.17.9.18": true,
"172.18.9.18": true,
"172.19.9.18": true,
"172.20.9.18": true,
"172.21.9.18": true,
"172.22.9.18": true,
"172.23.9.18": true,
"172.24.9.18": true,
"172.25.9.18": true,
"172.26.9.18": true,
"172.27.9.18": true,
"172.28.9.18": true,
"172.29.9.18": true,
"172.30.9.18": true,
"172.31.9.18": true,
"172.32.9.18": false,
} {
if IsLocalIPAddr(ip) != expected {
t.Errorf("ip %s expected %v, got %v", ip, expected, IsLocalIPAddr(ip))
}
}
}
func TestIsLocalIP(t *testing.T) {
for ip, expected := range map[string]bool{
"": false,
"invalid ip address": false,
"127.0.0.1": true,
"::1": true,
"182.56.9.18": false,
"192.168.9.18": true,
"10.168.9.18": true,
"11.168.9.18": false,
"172.16.9.18": true,
"172.17.9.18": true,
"172.18.9.18": true,
"172.19.9.18": true,
"172.20.9.18": true,
"172.21.9.18": true,
"172.22.9.18": true,
"172.23.9.18": true,
"172.24.9.18": true,
"172.25.9.18": true,
"172.26.9.18": true,
"172.27.9.18": true,
"172.28.9.18": true,
"172.29.9.18": true,
"172.30.9.18": true,
"172.31.9.18": true,
"172.32.9.18": false,
} {
if IsLocalIP(net.ParseIP(ip)) != expected {
t.Errorf("ip %s expected %v, got %v", ip, expected, IsLocalIP(net.ParseIP(ip)))
}
}
for ip, expected := range map[string]bool{
"": false,
"invalid ip address": false,
"127.0.0.1": true,
"::1": true,
"182.56.9.18": false,
"192.168.9.18": true,
"10.168.9.18": true,
"11.168.9.18": false,
"172.16.9.18": true,
"172.17.9.18": true,
"172.18.9.18": true,
"172.19.9.18": true,
"172.20.9.18": true,
"172.21.9.18": true,
"172.22.9.18": true,
"172.23.9.18": true,
"172.24.9.18": true,
"172.25.9.18": true,
"172.26.9.18": true,
"172.27.9.18": true,
"172.28.9.18": true,
"172.29.9.18": true,
"172.30.9.18": true,
"172.31.9.18": true,
"172.32.9.18": false,
} {
if IsLocalIP(net.ParseIP(ip)) != expected {
t.Errorf("ip %s expected %v, got %v", ip, expected, IsLocalIP(net.ParseIP(ip)))
}
}
}
func TestIPAddrToUint32(t *testing.T) {
for _, v := range []struct {
ip string
val uint32
}{
{"127.0.0.1", 2130706433},
{"0.0.0.0", 0},
{"255.255.255.255", 4294967295},
{"192.168.1.1", 3232235777},
} {
got, err := IPAddrToUint32(v.ip)
if err != nil {
t.Errorf("ip:%s expected %d, got:%d err:%v", v.ip, v.val, got, err)
}
if got != v.val {
t.Errorf("ip:%s expected %d, got:%d", v.ip, v.val, got)
}
}
for _, ip := range []string{
"",
"invalid ip address",
"::1",
} {
_, err := IPAddrToUint32(ip)
if err == nil {
t.Errorf("ip:%s invalid IP passes", ip)
}
}
for _, v := range []struct {
ip string
val uint32
}{
{"127.0.0.1", 2130706433},
{"0.0.0.0", 0},
{"255.255.255.255", 4294967295},
{"192.168.1.1", 3232235777},
} {
got, err := IPAddrToUint32(v.ip)
if err != nil {
t.Errorf("ip:%s expected %d, got:%d err:%v", v.ip, v.val, got, err)
}
if got != v.val {
t.Errorf("ip:%s expected %d, got:%d", v.ip, v.val, got)
}
}
for _, ip := range []string{
"",
"invalid ip address",
"::1",
} {
_, err := IPAddrToUint32(ip)
if err == nil {
t.Errorf("ip:%s invalid IP passes", ip)
}
}
}
func TestUint32ToIPAddr(t *testing.T) {
for _, v := range []struct {
ip string
val uint32
}{
{"127.0.0.1", 2130706433},
{"0.0.0.0", 0},
{"255.255.255.255", 4294967295},
{"192.168.1.1", 3232235777},
} {
got := Uint32ToIPAddr(v.val)
if got != v.ip {
t.Errorf("val: %d, expected:%s, got:%s", v.val, v.ip, got)
}
}
for _, v := range []struct {
ip string
val uint32
}{
{"127.0.0.1", 2130706433},
{"0.0.0.0", 0},
{"255.255.255.255", 4294967295},
{"192.168.1.1", 3232235777},
} {
got := Uint32ToIPAddr(v.val)
if got != v.ip {
t.Errorf("val: %d, expected:%s, got:%s", v.val, v.ip, got)
}
}
}
func TestIPToUint32(t *testing.T) {
for _, v := range []struct {
ip string
val uint32
}{
{"127.0.0.1", 2130706433},
{"0.0.0.0", 0},
{"255.255.255.255", 4294967295},
{"192.168.1.1", 3232235777},
} {
got, err := IPToUint32(net.ParseIP(v.ip))
if err != nil {
t.Errorf("ip:%s expected %d, got:%d err:%v", v.ip, v.val, got, err)
}
if got != v.val {
t.Errorf("ip:%s expected %d, got:%d", v.ip, v.val, got)
}
}
for _, ip := range []string{
"",
"invalid ip address",
"::1",
} {
_, err := IPToUint32(net.ParseIP(ip))
if err == nil {
t.Errorf("ip:%s invalid IP passes", ip)
}
}
for _, v := range []struct {
ip string
val uint32
}{
{"127.0.0.1", 2130706433},
{"0.0.0.0", 0},
{"255.255.255.255", 4294967295},
{"192.168.1.1", 3232235777},
} {
got, err := IPToUint32(net.ParseIP(v.ip))
if err != nil {
t.Errorf("ip:%s expected %d, got:%d err:%v", v.ip, v.val, got, err)
}
if got != v.val {
t.Errorf("ip:%s expected %d, got:%d", v.ip, v.val, got)
}
}
for _, ip := range []string{
"",
"invalid ip address",
"::1",
} {
_, err := IPToUint32(net.ParseIP(ip))
if err == nil {
t.Errorf("ip:%s invalid IP passes", ip)
}
}
}
func TestUint32ToIP(t *testing.T) {
for _, v := range []struct {
ip string
val uint32
}{
{"127.0.0.1", 2130706433},
{"0.0.0.0", 0},
{"255.255.255.255", 4294967295},
{"192.168.1.1", 3232235777},
} {
got := Uint32ToIP(v.val)
if got.String() != v.ip {
t.Errorf("val: %d, expected:%s, got:%s", v.val, v.ip, got)
}
}
for _, v := range []struct {
ip string
val uint32
}{
{"127.0.0.1", 2130706433},
{"0.0.0.0", 0},
{"255.255.255.255", 4294967295},
{"192.168.1.1", 3232235777},
} {
got := Uint32ToIP(v.val)
if got.String() != v.ip {
t.Errorf("val: %d, expected:%s, got:%s", v.val, v.ip, got)
}
}
}

130
json.go
View File

@ -1,93 +1,93 @@
package util
import (
"encoding/json"
"encoding/json"
)
type JSON struct {
result []byte
err error
isArray bool
result []byte
err error
isArray bool
}
func NewJSONResult(data []byte) *JSON {
m1 := make(map[string]any)
err1 := json.Unmarshal(data, &m1)
if err1 != nil {
m2 := make([]map[string]any, 0)
err2 := json.Unmarshal(data, &m2)
if err2 != nil {
return nil
}
return NewJSON(m2, true)
}
return NewJSON(m1, false)
m1 := make(map[string]any)
err1 := json.Unmarshal(data, &m1)
if err1 != nil {
m2 := make([]map[string]any, 0)
err2 := json.Unmarshal(data, &m2)
if err2 != nil {
return nil
}
return NewJSON(m2, true)
}
return NewJSON(m1, false)
}
func NewJSON(v any, isArray bool) *JSON {
res := &JSON{}
res.result, res.err = json.Marshal(v)
res.isArray = isArray
return res
res := &JSON{}
res.result, res.err = json.Marshal(v)
res.isArray = isArray
return res
}
func (j *JSON) Bytes() []byte {
return j.result
return j.result
}
func (j *JSON) String() string {
return string(j.result)
return string(j.result)
}
func (j *JSON) Map(idx ...int) map[string]any {
if j.result == nil {
return nil
}
if !j.isArray {
m := make(map[string]any)
err := json.Unmarshal(j.result, &m)
if err != nil {
return nil
}
return m
}
i := 0
if len(idx) > 0 {
i = idx[0]
}
m := make([]map[string]any, 0)
err := json.Unmarshal(j.result, &m)
if err != nil {
return nil
}
ml := len(m)
if ml == 0 {
return nil
}
if i >= ml {
i = ml - 1
}
return m[i]
if j.result == nil {
return nil
}
if !j.isArray {
m := make(map[string]any)
err := json.Unmarshal(j.result, &m)
if err != nil {
return nil
}
return m
}
i := 0
if len(idx) > 0 {
i = idx[0]
}
m := make([]map[string]any, 0)
err := json.Unmarshal(j.result, &m)
if err != nil {
return nil
}
ml := len(m)
if ml == 0 {
return nil
}
if i >= ml {
i = ml - 1
}
return m[i]
}
func (j *JSON) MapArray() []map[string]any {
if j.isArray {
m := make([]map[string]any, 0)
err := json.Unmarshal(j.result, &m)
if err != nil {
return nil
}
return m
} else {
m := make(map[string]any)
err := json.Unmarshal(j.result, &m)
if err != nil {
return nil
}
return []map[string]any{m}
}
if j.isArray {
m := make([]map[string]any, 0)
err := json.Unmarshal(j.result, &m)
if err != nil {
return nil
}
return m
} else {
m := make(map[string]any)
err := json.Unmarshal(j.result, &m)
if err != nil {
return nil
}
return []map[string]any{m}
}
}
func (j *JSON) Error() error {
return j.err
return j.err
}

View File

@ -1,52 +1,52 @@
package util
import (
"fmt"
"fmt"
)
func ExampleNewJSON() {
type TestStruct struct {
Name string `json:"name"`
Age int `json:"age"`
}
test1 := TestStruct{
Name: "Akvicor",
Age: 17,
}
res := NewJSON(&test1, false)
if res.Error() == nil {
fmt.Println(res.String())
fmt.Println(res.Bytes())
fmt.Println(res.Map())
fmt.Println(res.Map(0))
fmt.Println(res.Map(10))
fmt.Println(res.MapArray())
fmt.Println(NewJSON(res.Map(), false))
}
test2 := [...]TestStruct{{Name: "Akvicor", Age: 17}, {Name: "MIU", Age: 17}}
res = NewJSON(&test2, true)
if res.Error() == nil {
fmt.Println(res.Map(1))
fmt.Println(res.MapArray())
}
// Output:
// {"name":"Akvicor","age":17}
// [123 34 110 97 109 101 34 58 34 65 107 118 105 99 111 114 34 44 34 97 103 101 34 58 49 55 125]
// map[age:17 name:Akvicor]
// map[age:17 name:Akvicor]
// map[age:17 name:Akvicor]
// [map[age:17 name:Akvicor]]
// {"age":17,"name":"Akvicor"}
// map[age:17 name:MIU]
// [map[age:17 name:Akvicor] map[age:17 name:MIU]]
type TestStruct struct {
Name string `json:"name"`
Age int `json:"age"`
}
test1 := TestStruct{
Name: "Akvicor",
Age: 17,
}
res := NewJSON(&test1, false)
if res.Error() == nil {
fmt.Println(res.String())
fmt.Println(res.Bytes())
fmt.Println(res.Map())
fmt.Println(res.Map(0))
fmt.Println(res.Map(10))
fmt.Println(res.MapArray())
fmt.Println(NewJSON(res.Map(), false))
}
test2 := [...]TestStruct{{Name: "Akvicor", Age: 17}, {Name: "MIU", Age: 17}}
res = NewJSON(&test2, true)
if res.Error() == nil {
fmt.Println(res.Map(1))
fmt.Println(res.MapArray())
}
// Output:
// {"name":"Akvicor","age":17}
// [123 34 110 97 109 101 34 58 34 65 107 118 105 99 111 114 34 44 34 97 103 101 34 58 49 55 125]
// map[age:17 name:Akvicor]
// map[age:17 name:Akvicor]
// map[age:17 name:Akvicor]
// [map[age:17 name:Akvicor]]
// {"age":17,"name":"Akvicor"}
// map[age:17 name:MIU]
// [map[age:17 name:Akvicor] map[age:17 name:MIU]]
}
func ExampleNewJSONResult() {
fmt.Println(NewJSONResult([]byte(`{"name":"Akvicor","age":17}`)).Map())
fmt.Println(NewJSONResult([]byte(`[{"name":"Akvicor","age":17}]`)).Map())
// Output:
// map[age:17 name:Akvicor]
// map[age:17 name:Akvicor]
fmt.Println(NewJSONResult([]byte(`{"name":"Akvicor","age":17}`)).Map())
fmt.Println(NewJSONResult([]byte(`[{"name":"Akvicor","age":17}]`)).Map())
// Output:
// map[age:17 name:Akvicor]
// map[age:17 name:Akvicor]
}

166
md5.go
View File

@ -1,151 +1,151 @@
package util
import (
"crypto/md5"
"encoding/hex"
"errors"
"hash"
"io"
"os"
"path/filepath"
"strings"
"crypto/md5"
"encoding/hex"
"errors"
"hash"
"io"
"os"
"path/filepath"
"strings"
)
const MD5ResultLength = 16
type MD5Result struct {
result [MD5ResultLength]byte
err error
result [MD5ResultLength]byte
err error
}
func (m *MD5Result) Array() [MD5ResultLength]byte {
return m.result
return m.result
}
func (m *MD5Result) Slice() []byte {
return m.result[:]
return m.result[:]
}
func (m *MD5Result) Upper() string {
return strings.ToUpper(hex.EncodeToString(m.result[:]))
return strings.ToUpper(hex.EncodeToString(m.result[:]))
}
func (m *MD5Result) Lower() string {
return strings.ToLower(hex.EncodeToString(m.result[:]))
return strings.ToLower(hex.EncodeToString(m.result[:]))
}
func (m *MD5Result) Error() error {
return m.err
return m.err
}
func NewMD5Result(result []byte, err error) *MD5Result {
res := &MD5Result{
result: [MD5ResultLength]byte{},
err: err,
}
copy(res.result[:], result)
return res
res := &MD5Result{
result: [MD5ResultLength]byte{},
err: err,
}
copy(res.result[:], result)
return res
}
type MD5 struct{}
func NewMD5() *MD5 {
return &MD5{}
return &MD5{}
}
func (m *MD5) FromReader(r io.Reader) *MD5Result {
ha := md5.New()
if _, err := io.Copy(ha, r); err != nil {
return NewMD5Result(nil, err)
}
hashInBytes := ha.Sum(nil)
if len(hashInBytes) != MD5ResultLength {
return NewMD5Result(nil, errors.New("wrong length"))
}
return NewMD5Result(hashInBytes, nil)
ha := md5.New()
if _, err := io.Copy(ha, r); err != nil {
return NewMD5Result(nil, err)
}
hashInBytes := ha.Sum(nil)
if len(hashInBytes) != MD5ResultLength {
return NewMD5Result(nil, errors.New("wrong length"))
}
return NewMD5Result(hashInBytes, nil)
}
func (m *MD5) FromFile(filename string) *MD5Result {
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewMD5Result(nil, err)
}
defer func() {
_ = file.Close()
}()
return m.FromReader(file)
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewMD5Result(nil, err)
}
defer func() {
_ = file.Close()
}()
return m.FromReader(file)
}
func (m *MD5) FromReaderChunk(r io.Reader, chunksize int) *MD5Result {
buf := make([]byte, chunksize)
m5 := md5.New()
var n int
var err error
for {
n, err = r.Read(buf)
if err != nil {
if err != io.EOF {
return NewMD5Result(nil, err)
}
if n > 0 {
_, err = m5.Write(buf[:n])
if err != nil {
return NewMD5Result(nil, err)
}
}
break
}
_, err = m5.Write(buf[:n])
if err != nil {
return NewMD5Result(nil, err)
}
}
return NewMD5Result(m5.Sum(nil), nil)
buf := make([]byte, chunksize)
m5 := md5.New()
var n int
var err error
for {
n, err = r.Read(buf)
if err != nil {
if err != io.EOF {
return NewMD5Result(nil, err)
}
if n > 0 {
_, err = m5.Write(buf[:n])
if err != nil {
return NewMD5Result(nil, err)
}
}
break
}
_, err = m5.Write(buf[:n])
if err != nil {
return NewMD5Result(nil, err)
}
}
return NewMD5Result(m5.Sum(nil), nil)
}
func (m *MD5) FromFileChunk(filename string, chunksize int) *MD5Result {
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewMD5Result(nil, err)
}
defer func() {
_ = file.Close()
}()
return m.FromReaderChunk(file, chunksize)
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewMD5Result(nil, err)
}
defer func() {
_ = file.Close()
}()
return m.FromReaderChunk(file, chunksize)
}
func (m *MD5) FromBytes(b []byte) *MD5Result {
res := md5.Sum(b)
return NewMD5Result(res[:], nil)
res := md5.Sum(b)
return NewMD5Result(res[:], nil)
}
func (m *MD5) FromString(str string) *MD5Result {
res := md5.Sum([]byte(str))
return NewMD5Result(res[:], nil)
res := md5.Sum([]byte(str))
return NewMD5Result(res[:], nil)
}
type MD5Pip struct {
md5 hash.Hash
md5 hash.Hash
}
func NewMD5Pip() *MD5Pip {
return &MD5Pip{md5: md5.New()}
return &MD5Pip{md5: md5.New()}
}
func (m *MD5Pip) Write(data []byte) (n int, err error) {
return m.md5.Write(data)
return m.md5.Write(data)
}
func (m *MD5Pip) WriteBytes(data []byte) error {
_, err := m.Write(data)
return err
_, err := m.Write(data)
return err
}
func (m *MD5Pip) WriteString(data string) error {
_, err := m.Write([]byte(data))
return err
_, err := m.Write([]byte(data))
return err
}
func (m *MD5Pip) Result() *MD5Result {
return NewMD5Result(m.md5.Sum(nil), nil)
return NewMD5Result(m.md5.Sum(nil), nil)
}

View File

@ -1,167 +1,167 @@
package util
import (
"bytes"
"encoding/hex"
"fmt"
"io"
"strings"
"testing"
"bytes"
"encoding/hex"
"fmt"
"io"
"strings"
"testing"
)
func TestMD5(t *testing.T) {
// dd if=/dev/zero of=testfile/testFile1 bs=4KB count=4
// md5sum testFile1
const fileMD5 = "1ee0193671609c7d63cfe89b920ad313"
fileMD5Bytes, err := hex.DecodeString(fileMD5)
if err != nil {
t.Errorf("fileMD5Bytes: %v", err)
}
testString := "Akvicor"
testBytes := []byte(testString)
testStringP1 := "Akv"
testStringP2 := "icor"
testBytesP1 := []byte(testStringP1)
testBytesP2 := []byte(testStringP2)
testMD5 := "f812705c26adc52561415189e5f78edb"
testMD5P1 := "d1c13e1e2aa77bed0a694fe1b375a3aa"
// test FromFile & MD5Result
m5 := NewMD5().FromFile("testfile/testFile1")
if m5.Error() != nil {
t.Errorf("FromFile failed: %v", m5.Error())
}
if m5.Lower() != fileMD5 {
t.Errorf("FromFile failed: expected: [%s] got [%s]", fileMD5, m5.Lower())
}
if m5.Upper() != strings.ToUpper(fileMD5) {
t.Errorf("FromFile failed: expected: [%s] got [%s]", strings.ToUpper(fileMD5), m5.Upper())
}
if !bytes.Equal(m5.Slice(), fileMD5Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileMD5Bytes, m5.Slice())
}
ay := m5.Array()
if !bytes.Equal(ay[:], fileMD5Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileMD5Bytes, ay)
}
// test FromFileChunk
m5 = NewMD5().FromFileChunk("testfile/testFile1", 1024*64)
if m5.Error() != nil {
t.Errorf("FromFileChunk failed: %v", m5.Error())
}
if m5.Lower() != fileMD5 {
t.Errorf("FromFileChunk failed: expected: [%s] got [%s]", fileMD5, m5.Lower())
}
// test FromBytes
m5 = NewMD5().FromBytes(testBytes)
if m5.Error() != nil {
t.Errorf("FromBytes failed: %v", m5.Error())
}
if m5.Lower() != testMD5 {
t.Errorf("FromBytes failed: expected: [%s] got [%s]", testMD5, m5.Lower())
}
// test FromString
m5 = NewMD5().FromString(testString)
if m5.Error() != nil {
t.Errorf("FromString failed: %v", m5.Error())
}
if m5.Lower() != testMD5 {
t.Errorf("FromString failed: expected: [%s] got [%s]", testMD5, m5.Lower())
}
// test NewMD5Pip.WriteBytes
mp := NewMD5Pip()
err = mp.WriteBytes(testBytesP1)
if err != nil {
t.Errorf("NewMD5Pip WriteBytes failed: %v", err)
}
err = mp.WriteBytes(testBytesP2)
if err != nil {
t.Errorf("NewMD5Pip WriteBytes failed: %v", err)
}
m5 = mp.Result()
if m5.Error() != nil {
t.Errorf("NewMD5Pip WriteBytes failed: %v", m5.Error())
}
if m5.Lower() != testMD5 {
t.Errorf("NewMD5Pip WriteBytes failed: expected: [%s] got [%s]", testMD5, m5.Lower())
}
// test NewMD5Pip.WriteString
mp = NewMD5Pip()
err = mp.WriteString(testStringP1)
if err != nil {
t.Errorf("NewMD5Pip WriteString failed: %v", err)
}
err = mp.WriteString(testStringP2)
if err != nil {
t.Errorf("NewMD5Pip WriteString failed: %v", err)
}
m5 = mp.Result()
if m5.Error() != nil {
t.Errorf("NewMD5Pip WriteString failed: %v", m5.Error())
}
if m5.Lower() != testMD5 {
t.Errorf("NewMD5Pip WriteString failed: expected: [%s] got [%s]", testMD5, m5.Lower())
}
// test NewMD5Pip.Result
mp = NewMD5Pip()
err = mp.WriteString(testStringP1)
if err != nil {
t.Errorf("NewMD5Pip WriteString failed: %v", err)
}
m5 = mp.Result()
if m5.Error() != nil {
t.Errorf("NewMD5Pip WriteString failed: %v", m5.Error())
}
if m5.Lower() != testMD5P1 {
t.Errorf("NewMD5Pip WriteString failed: expected: [%s] got [%s]", testMD5P1, m5.Lower())
}
err = mp.WriteString(testStringP2)
if err != nil {
t.Errorf("NewMD5Pip WriteString failed: %v", err)
}
m5 = mp.Result()
if m5.Error() != nil {
t.Errorf("NewMD5Pip WriteString failed: %v", m5.Error())
}
if m5.Lower() != testMD5 {
t.Errorf("NewMD5Pip WriteString failed: expected: [%s] got [%s]", testMD5, m5.Lower())
}
// dd if=/dev/zero of=testfile/testFile1 bs=4KB count=4
// md5sum testFile1
const fileMD5 = "1ee0193671609c7d63cfe89b920ad313"
fileMD5Bytes, err := hex.DecodeString(fileMD5)
if err != nil {
t.Errorf("fileMD5Bytes: %v", err)
}
testString := "Akvicor"
testBytes := []byte(testString)
testStringP1 := "Akv"
testStringP2 := "icor"
testBytesP1 := []byte(testStringP1)
testBytesP2 := []byte(testStringP2)
testMD5 := "f812705c26adc52561415189e5f78edb"
testMD5P1 := "d1c13e1e2aa77bed0a694fe1b375a3aa"
// test FromFile & MD5Result
m5 := NewMD5().FromFile("testfile/testFile1")
if m5.Error() != nil {
t.Errorf("FromFile failed: %v", m5.Error())
}
if m5.Lower() != fileMD5 {
t.Errorf("FromFile failed: expected: [%s] got [%s]", fileMD5, m5.Lower())
}
if m5.Upper() != strings.ToUpper(fileMD5) {
t.Errorf("FromFile failed: expected: [%s] got [%s]", strings.ToUpper(fileMD5), m5.Upper())
}
if !bytes.Equal(m5.Slice(), fileMD5Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileMD5Bytes, m5.Slice())
}
ay := m5.Array()
if !bytes.Equal(ay[:], fileMD5Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileMD5Bytes, ay)
}
// test FromFileChunk
m5 = NewMD5().FromFileChunk("testfile/testFile1", 1024*64)
if m5.Error() != nil {
t.Errorf("FromFileChunk failed: %v", m5.Error())
}
if m5.Lower() != fileMD5 {
t.Errorf("FromFileChunk failed: expected: [%s] got [%s]", fileMD5, m5.Lower())
}
// test FromBytes
m5 = NewMD5().FromBytes(testBytes)
if m5.Error() != nil {
t.Errorf("FromBytes failed: %v", m5.Error())
}
if m5.Lower() != testMD5 {
t.Errorf("FromBytes failed: expected: [%s] got [%s]", testMD5, m5.Lower())
}
// test FromString
m5 = NewMD5().FromString(testString)
if m5.Error() != nil {
t.Errorf("FromString failed: %v", m5.Error())
}
if m5.Lower() != testMD5 {
t.Errorf("FromString failed: expected: [%s] got [%s]", testMD5, m5.Lower())
}
// test NewMD5Pip.WriteBytes
mp := NewMD5Pip()
err = mp.WriteBytes(testBytesP1)
if err != nil {
t.Errorf("NewMD5Pip WriteBytes failed: %v", err)
}
err = mp.WriteBytes(testBytesP2)
if err != nil {
t.Errorf("NewMD5Pip WriteBytes failed: %v", err)
}
m5 = mp.Result()
if m5.Error() != nil {
t.Errorf("NewMD5Pip WriteBytes failed: %v", m5.Error())
}
if m5.Lower() != testMD5 {
t.Errorf("NewMD5Pip WriteBytes failed: expected: [%s] got [%s]", testMD5, m5.Lower())
}
// test NewMD5Pip.WriteString
mp = NewMD5Pip()
err = mp.WriteString(testStringP1)
if err != nil {
t.Errorf("NewMD5Pip WriteString failed: %v", err)
}
err = mp.WriteString(testStringP2)
if err != nil {
t.Errorf("NewMD5Pip WriteString failed: %v", err)
}
m5 = mp.Result()
if m5.Error() != nil {
t.Errorf("NewMD5Pip WriteString failed: %v", m5.Error())
}
if m5.Lower() != testMD5 {
t.Errorf("NewMD5Pip WriteString failed: expected: [%s] got [%s]", testMD5, m5.Lower())
}
// test NewMD5Pip.Result
mp = NewMD5Pip()
err = mp.WriteString(testStringP1)
if err != nil {
t.Errorf("NewMD5Pip WriteString failed: %v", err)
}
m5 = mp.Result()
if m5.Error() != nil {
t.Errorf("NewMD5Pip WriteString failed: %v", m5.Error())
}
if m5.Lower() != testMD5P1 {
t.Errorf("NewMD5Pip WriteString failed: expected: [%s] got [%s]", testMD5P1, m5.Lower())
}
err = mp.WriteString(testStringP2)
if err != nil {
t.Errorf("NewMD5Pip WriteString failed: %v", err)
}
m5 = mp.Result()
if m5.Error() != nil {
t.Errorf("NewMD5Pip WriteString failed: %v", m5.Error())
}
if m5.Lower() != testMD5 {
t.Errorf("NewMD5Pip WriteString failed: expected: [%s] got [%s]", testMD5, m5.Lower())
}
}
func ExampleNewMD5() {
m5 := NewMD5()
res := m5.FromString("Akvicor")
if res.Error() == nil {
fmt.Println(res.Lower())
fmt.Println(res.Upper())
fmt.Println(res.Slice())
}
// Output:
// f812705c26adc52561415189e5f78edb
// F812705C26ADC52561415189E5F78EDB
// [248 18 112 92 38 173 197 37 97 65 81 137 229 247 142 219]
m5 := NewMD5()
res := m5.FromString("Akvicor")
if res.Error() == nil {
fmt.Println(res.Lower())
fmt.Println(res.Upper())
fmt.Println(res.Slice())
}
// Output:
// f812705c26adc52561415189e5f78edb
// F812705C26ADC52561415189E5F78EDB
// [248 18 112 92 38 173 197 37 97 65 81 137 229 247 142 219]
}
func ExampleNewMD5Pip() {
mp := NewMD5Pip()
_, err := io.WriteString(mp, "Akvicor")
if err != nil {
fmt.Println(err)
}
res := mp.Result()
if res.Error() == nil {
fmt.Println(res.Array())
fmt.Println(res.Slice())
}
// Output:
// [248 18 112 92 38 173 197 37 97 65 81 137 229 247 142 219]
// [248 18 112 92 38 173 197 37 97 65 81 137 229 247 142 219]
mp := NewMD5Pip()
_, err := io.WriteString(mp, "Akvicor")
if err != nil {
fmt.Println(err)
}
res := mp.Result()
if res.Error() == nil {
fmt.Println(res.Array())
fmt.Println(res.Slice())
}
// Output:
// [248 18 112 92 38 173 197 37 97 65 81 137 229 247 142 219]
// [248 18 112 92 38 173 197 37 97 65 81 137 229 247 142 219]
}

58
path.go
View File

@ -1,42 +1,42 @@
package util
import (
"path"
"strings"
"path"
"strings"
)
func SplitPathSkip(p string, skip int) (head, tail string) {
p = path.Clean("/" + p + "/")
fin := 0
cur := 0
for skip >= 0 {
skip--
if fin+1 >= len(p) {
return p, ""
}
cur = strings.IndexByte(p[fin+1:], '/')
if cur < 0 {
return p, ""
}
fin += cur + 1
}
return p[:fin], p[fin:]
p = path.Clean("/" + p + "/")
fin := 0
cur := 0
for skip >= 0 {
skip--
if fin+1 >= len(p) {
return p, ""
}
cur = strings.IndexByte(p[fin+1:], '/')
if cur < 0 {
return p, ""
}
fin += cur + 1
}
return p[:fin], p[fin:]
}
func SplitPath(p string) (head, tail string) {
p = path.Clean("/" + p + "/")
return SplitPathSkip(p, 0)
p = path.Clean("/" + p + "/")
return SplitPathSkip(p, 0)
}
func SplitPathRepeat(p string, repeat int) (head, tail string) {
p = path.Clean("/" + p + "/")
head, tail = SplitPathSkip(p, repeat)
c := strings.Count(head, "/") - 1
if c == repeat {
i := strings.LastIndexByte(head, '/')
return head[i:], tail
} else if c < repeat {
return "/", ""
}
return head, tail
p = path.Clean("/" + p + "/")
head, tail = SplitPathSkip(p, repeat)
c := strings.Count(head, "/") - 1
if c == repeat {
i := strings.LastIndexByte(head, '/')
return head[i:], tail
} else if c < repeat {
return "/", ""
}
return head, tail
}

View File

@ -3,124 +3,124 @@ package util
import "fmt"
func ExampleSplitPathSkip() {
test := func(s string, skip int) {
head, tail := SplitPathSkip(s, skip)
fmt.Printf("s[%s] skip[%d] -> [%s, %s]\n", s, skip, head, tail)
}
s := "/1/23/456/7/"
test(s, 0)
test(s, 1)
test(s, 2)
test(s, 3)
test(s, 4)
s = ""
test(s, 0)
test(s, 1)
s = "/"
test(s, 0)
test(s, 1)
s = "url"
test(s, 0)
test(s, 1)
s = "/url"
test(s, 0)
test(s, 1)
s = "url/"
test(s, 0)
test(s, 1)
s = "/url/"
test(s, 0)
test(s, 1)
// Output:
// s[/1/23/456/7/] skip[0] -> [/1, /23/456/7]
// s[/1/23/456/7/] skip[1] -> [/1/23, /456/7]
// s[/1/23/456/7/] skip[2] -> [/1/23/456, /7]
// s[/1/23/456/7/] skip[3] -> [/1/23/456/7, ]
// s[/1/23/456/7/] skip[4] -> [/1/23/456/7, ]
// s[] skip[0] -> [/, ]
// s[] skip[1] -> [/, ]
// s[/] skip[0] -> [/, ]
// s[/] skip[1] -> [/, ]
// s[url] skip[0] -> [/url, ]
// s[url] skip[1] -> [/url, ]
// s[/url] skip[0] -> [/url, ]
// s[/url] skip[1] -> [/url, ]
// s[url/] skip[0] -> [/url, ]
// s[url/] skip[1] -> [/url, ]
// s[/url/] skip[0] -> [/url, ]
// s[/url/] skip[1] -> [/url, ]
test := func(s string, skip int) {
head, tail := SplitPathSkip(s, skip)
fmt.Printf("s[%s] skip[%d] -> [%s, %s]\n", s, skip, head, tail)
}
s := "/1/23/456/7/"
test(s, 0)
test(s, 1)
test(s, 2)
test(s, 3)
test(s, 4)
s = ""
test(s, 0)
test(s, 1)
s = "/"
test(s, 0)
test(s, 1)
s = "url"
test(s, 0)
test(s, 1)
s = "/url"
test(s, 0)
test(s, 1)
s = "url/"
test(s, 0)
test(s, 1)
s = "/url/"
test(s, 0)
test(s, 1)
// Output:
// s[/1/23/456/7/] skip[0] -> [/1, /23/456/7]
// s[/1/23/456/7/] skip[1] -> [/1/23, /456/7]
// s[/1/23/456/7/] skip[2] -> [/1/23/456, /7]
// s[/1/23/456/7/] skip[3] -> [/1/23/456/7, ]
// s[/1/23/456/7/] skip[4] -> [/1/23/456/7, ]
// s[] skip[0] -> [/, ]
// s[] skip[1] -> [/, ]
// s[/] skip[0] -> [/, ]
// s[/] skip[1] -> [/, ]
// s[url] skip[0] -> [/url, ]
// s[url] skip[1] -> [/url, ]
// s[/url] skip[0] -> [/url, ]
// s[/url] skip[1] -> [/url, ]
// s[url/] skip[0] -> [/url, ]
// s[url/] skip[1] -> [/url, ]
// s[/url/] skip[0] -> [/url, ]
// s[/url/] skip[1] -> [/url, ]
}
func ExampleSplitPath() {
test := func(s string) {
head, tail := SplitPath(s)
fmt.Printf("s[%s] -> [%s, %s]\n", s, head, tail)
}
test("/123/akvicor")
test("123/akvicor")
test("/akvicor")
test("akvicor")
test("/")
test("")
// Output:
// s[/123/akvicor] -> [/123, /akvicor]
// s[123/akvicor] -> [/123, /akvicor]
// s[/akvicor] -> [/akvicor, ]
// s[akvicor] -> [/akvicor, ]
// s[/] -> [/, ]
// s[] -> [/, ]
test := func(s string) {
head, tail := SplitPath(s)
fmt.Printf("s[%s] -> [%s, %s]\n", s, head, tail)
}
test("/123/akvicor")
test("123/akvicor")
test("/akvicor")
test("akvicor")
test("/")
test("")
// Output:
// s[/123/akvicor] -> [/123, /akvicor]
// s[123/akvicor] -> [/123, /akvicor]
// s[/akvicor] -> [/akvicor, ]
// s[akvicor] -> [/akvicor, ]
// s[/] -> [/, ]
// s[] -> [/, ]
}
func ExampleSplitPathRepeat() {
test := func(s string, repeat int) {
head, tail := SplitPathRepeat(s, repeat)
fmt.Printf("s[%s] repeat[%d] -> [%s, %s]\n", s, repeat, head, tail)
}
s := "/1/23/456/7/"
test(s, 0)
test(s, 1)
test(s, 2)
test(s, 3)
test(s, 4)
test(s, 5)
s = ""
test(s, 0)
test(s, 1)
s = "/"
test(s, 0)
test(s, 1)
s = "url"
test(s, 0)
test(s, 1)
s = "/url"
test(s, 0)
test(s, 1)
s = "url/"
test(s, 0)
test(s, 1)
s = "/url/"
test(s, 0)
test(s, 1)
// Output:
// s[/1/23/456/7/] repeat[0] -> [/1, /23/456/7]
// s[/1/23/456/7/] repeat[1] -> [/23, /456/7]
// s[/1/23/456/7/] repeat[2] -> [/456, /7]
// s[/1/23/456/7/] repeat[3] -> [/7, ]
// s[/1/23/456/7/] repeat[4] -> [/, ]
// s[/1/23/456/7/] repeat[5] -> [/, ]
// s[] repeat[0] -> [/, ]
// s[] repeat[1] -> [/, ]
// s[/] repeat[0] -> [/, ]
// s[/] repeat[1] -> [/, ]
// s[url] repeat[0] -> [/url, ]
// s[url] repeat[1] -> [/, ]
// s[/url] repeat[0] -> [/url, ]
// s[/url] repeat[1] -> [/, ]
// s[url/] repeat[0] -> [/url, ]
// s[url/] repeat[1] -> [/, ]
// s[/url/] repeat[0] -> [/url, ]
// s[/url/] repeat[1] -> [/, ]
test := func(s string, repeat int) {
head, tail := SplitPathRepeat(s, repeat)
fmt.Printf("s[%s] repeat[%d] -> [%s, %s]\n", s, repeat, head, tail)
}
s := "/1/23/456/7/"
test(s, 0)
test(s, 1)
test(s, 2)
test(s, 3)
test(s, 4)
test(s, 5)
s = ""
test(s, 0)
test(s, 1)
s = "/"
test(s, 0)
test(s, 1)
s = "url"
test(s, 0)
test(s, 1)
s = "/url"
test(s, 0)
test(s, 1)
s = "url/"
test(s, 0)
test(s, 1)
s = "/url/"
test(s, 0)
test(s, 1)
// Output:
// s[/1/23/456/7/] repeat[0] -> [/1, /23/456/7]
// s[/1/23/456/7/] repeat[1] -> [/23, /456/7]
// s[/1/23/456/7/] repeat[2] -> [/456, /7]
// s[/1/23/456/7/] repeat[3] -> [/7, ]
// s[/1/23/456/7/] repeat[4] -> [/, ]
// s[/1/23/456/7/] repeat[5] -> [/, ]
// s[] repeat[0] -> [/, ]
// s[] repeat[1] -> [/, ]
// s[/] repeat[0] -> [/, ]
// s[/] repeat[1] -> [/, ]
// s[url] repeat[0] -> [/url, ]
// s[url] repeat[1] -> [/, ]
// s[/url] repeat[0] -> [/url, ]
// s[/url] repeat[1] -> [/, ]
// s[url/] repeat[0] -> [/url, ]
// s[url/] repeat[1] -> [/, ]
// s[/url/] repeat[0] -> [/url, ]
// s[/url/] repeat[1] -> [/, ]
}

30
port.go
View File

@ -1,25 +1,25 @@
package util
import (
"fmt"
"net"
"time"
"fmt"
"net"
"time"
)
func TcpPortIsOpen(ip, port string) bool {
conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%s", ip, port), 3*time.Second)
if err != nil {
return false
}
defer conn.Close()
return true
conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%s", ip, port), 3*time.Second)
if err != nil {
return false
}
defer conn.Close()
return true
}
func TcpPortIsOpenByAddr(ipPort string) bool {
conn, err := net.DialTimeout("tcp", ipPort, 3*time.Second)
if err != nil {
return false
}
defer conn.Close()
return true
conn, err := net.DialTimeout("tcp", ipPort, 3*time.Second)
if err != nil {
return false
}
defer conn.Close()
return true
}

View File

@ -3,28 +3,28 @@ package util
import "fmt"
func ExampleTcpPortIsOpen() {
ip := "172.16.0.1"
fmt.Println(TcpPortIsOpen(ip, "22"))
fmt.Println(TcpPortIsOpen(ip, "80"))
fmt.Println(TcpPortIsOpen(ip, "443"))
fmt.Println(TcpPortIsOpen(ip, "444"))
// Output:
// true
// true
// true
// false
ip := "172.16.0.1"
fmt.Println(TcpPortIsOpen(ip, "22"))
fmt.Println(TcpPortIsOpen(ip, "80"))
fmt.Println(TcpPortIsOpen(ip, "443"))
fmt.Println(TcpPortIsOpen(ip, "444"))
// Output:
// true
// true
// true
// false
}
func ExampleTcpPortIsOpenByAddr() {
fmt.Println(TcpPortIsOpenByAddr("172.16.0.1:22"))
fmt.Println(TcpPortIsOpenByAddr("172.16.0.1:80"))
fmt.Println(TcpPortIsOpenByAddr("172.16.0.1:443"))
fmt.Println(TcpPortIsOpenByAddr("172.16.0.1:444"))
// Output:
// true
// true
// true
// false
fmt.Println(TcpPortIsOpenByAddr("172.16.0.1:22"))
fmt.Println(TcpPortIsOpenByAddr("172.16.0.1:80"))
fmt.Println(TcpPortIsOpenByAddr("172.16.0.1:443"))
fmt.Println(TcpPortIsOpenByAddr("172.16.0.1:444"))
// Output:
// true
// true
// true
// false
}

160
random.go
View File

@ -1,9 +1,9 @@
package util
import (
"crypto/rand"
"math/big"
"time"
"crypto/rand"
"math/big"
"time"
)
const RandomLower = "abcdefghijklmnopqrstuvwxyz"
@ -16,92 +16,92 @@ const RandomAll = RandomAlpha + RandomDigit + RandomSpecial
var RandomSlice = []string{RandomLower, RandomUpper, RandomDigit, RandomSpecial}
func RandomString(length int, str ...string) string {
chars := RandomAll
if len(str) != 0 {
chars = ""
for _, v := range str {
chars += v
}
}
charsLen := len(chars)
res := make([]byte, length)
for i := range res {
r, err := rand.Int(rand.Reader, big.NewInt(int64(charsLen)))
if err != nil {
return ""
}
res[i] = chars[r.Int64()]
}
return string(res)
chars := RandomAll
if len(str) != 0 {
chars = ""
for _, v := range str {
chars += v
}
}
charsLen := len(chars)
res := make([]byte, length)
for i := range res {
r, err := rand.Int(rand.Reader, big.NewInt(int64(charsLen)))
if err != nil {
return ""
}
res[i] = chars[r.Int64()]
}
return string(res)
}
func RandomStringAtLeastOnce(length int, str ...string) string {
chars := RandomSlice
charsLen := len(RandomSlice)
if len(str) != 0 {
chars = str
charsLen = len(str)
}
charsPerLen := make([]int, charsLen)
for i := range charsPerLen {
charsPerLen[i] = len(chars[i])
}
res := make([]byte, length)
i := 0
for ; i < charsLen && i < length; i++ {
r, err := rand.Int(rand.Reader, big.NewInt(int64(charsPerLen[i])))
if err != nil {
return ""
}
res[i] = chars[i][r.Int64()]
}
for ; i < length; i++ {
r, err := rand.Int(rand.Reader, big.NewInt(int64(charsLen)))
if err != nil {
return ""
}
t := r.Int64()
r2, err := rand.Int(rand.Reader, big.NewInt(int64(charsPerLen[t])))
if err != nil {
return ""
}
res[i] = chars[t][r2.Int64()]
}
for i = range res {
t, err := rand.Int(rand.Reader, big.NewInt(int64(length)))
if err != nil {
return ""
}
res[i], res[t.Int64()] = res[t.Int64()], res[i]
}
return string(res)
chars := RandomSlice
charsLen := len(RandomSlice)
if len(str) != 0 {
chars = str
charsLen = len(str)
}
charsPerLen := make([]int, charsLen)
for i := range charsPerLen {
charsPerLen[i] = len(chars[i])
}
res := make([]byte, length)
i := 0
for ; i < charsLen && i < length; i++ {
r, err := rand.Int(rand.Reader, big.NewInt(int64(charsPerLen[i])))
if err != nil {
return ""
}
res[i] = chars[i][r.Int64()]
}
for ; i < length; i++ {
r, err := rand.Int(rand.Reader, big.NewInt(int64(charsLen)))
if err != nil {
return ""
}
t := r.Int64()
r2, err := rand.Int(rand.Reader, big.NewInt(int64(charsPerLen[t])))
if err != nil {
return ""
}
res[i] = chars[t][r2.Int64()]
}
for i = range res {
t, err := rand.Int(rand.Reader, big.NewInt(int64(length)))
if err != nil {
return ""
}
res[i], res[t.Int64()] = res[t.Int64()], res[i]
}
return string(res)
}
const RandomStringWithTimestampTimeLength = 8
func RandomStringWithTimestamp(length int, unix ...int64) string {
if length < RandomStringWithTimestampTimeLength {
length = RandomStringWithTimestampTimeLength
}
var t int64
if len(unix) > 0 {
t = unix[0]
} else {
t = time.Now().Unix()
}
return TimeUnixToBase36(t, RandomStringWithTimestampTimeLength) + RandomString(length-RandomStringWithTimestampTimeLength)
if length < RandomStringWithTimestampTimeLength {
length = RandomStringWithTimestampTimeLength
}
var t int64
if len(unix) > 0 {
t = unix[0]
} else {
t = time.Now().Unix()
}
return TimeUnixToBase36(t, RandomStringWithTimestampTimeLength) + RandomString(length-RandomStringWithTimestampTimeLength)
}
func ParseRandomStringWithTimestamp(str string) (int64, string) {
if len(str) < RandomStringWithTimestampTimeLength {
return 0, ""
}
t := TimeBase36ToUnix(string([]byte(str)[:RandomStringWithTimestampTimeLength]))
if t == 0 {
return 0, ""
}
return t, string([]byte(str)[RandomStringWithTimestampTimeLength:])
if len(str) < RandomStringWithTimestampTimeLength {
return 0, ""
}
t := TimeBase36ToUnix(string([]byte(str)[:RandomStringWithTimestampTimeLength]))
if t == 0 {
return 0, ""
}
return t, string([]byte(str)[RandomStringWithTimestampTimeLength:])
}

View File

@ -1,75 +1,75 @@
package util
import (
"fmt"
"time"
"fmt"
"time"
)
func ExampleRandomString() {
if RandomString(0, "a") != "" {
fmt.Println("1 failed")
}
if RandomString(0, "abc") != "" {
fmt.Println("2 failed")
}
if RandomString(1, "b") != "b" {
fmt.Println("3 failed")
}
if RandomString(7, "a") != "aaaaaaa" {
fmt.Println("4 failed")
}
if RandomString(0, "a", "b") != "" {
fmt.Println("5 failed")
}
str := RandomString(7)
if len(str) != 7 {
fmt.Println("6 failed")
}
// Output:
//
if RandomString(0, "a") != "" {
fmt.Println("1 failed")
}
if RandomString(0, "abc") != "" {
fmt.Println("2 failed")
}
if RandomString(1, "b") != "b" {
fmt.Println("3 failed")
}
if RandomString(7, "a") != "aaaaaaa" {
fmt.Println("4 failed")
}
if RandomString(0, "a", "b") != "" {
fmt.Println("5 failed")
}
str := RandomString(7)
if len(str) != 7 {
fmt.Println("6 failed")
}
// Output:
//
}
func ExampleRandomStringAtLeastOnce() {
if RandomStringAtLeastOnce(0, "a") != "" {
fmt.Println("1 failed")
}
if RandomStringAtLeastOnce(0, "abc") != "" {
fmt.Println("2 failed")
}
if RandomStringAtLeastOnce(1, "b") != "b" {
fmt.Println("3 failed")
}
if RandomStringAtLeastOnce(7, "a") != "aaaaaaa" {
fmt.Println("4 failed")
}
if RandomStringAtLeastOnce(0, "a", "b") != "" {
fmt.Println("5 failed")
}
str := RandomStringAtLeastOnce(2, "a", "b")
if str != "ab" && str != "ba" {
fmt.Println("6 failed", str)
}
if RandomStringAtLeastOnce(1, "a", "b") != "a" {
fmt.Println("7 failed")
}
str = RandomStringAtLeastOnce(7)
if len(str) != 7 {
fmt.Println("8 failed")
}
// Output:
//
if RandomStringAtLeastOnce(0, "a") != "" {
fmt.Println("1 failed")
}
if RandomStringAtLeastOnce(0, "abc") != "" {
fmt.Println("2 failed")
}
if RandomStringAtLeastOnce(1, "b") != "b" {
fmt.Println("3 failed")
}
if RandomStringAtLeastOnce(7, "a") != "aaaaaaa" {
fmt.Println("4 failed")
}
if RandomStringAtLeastOnce(0, "a", "b") != "" {
fmt.Println("5 failed")
}
str := RandomStringAtLeastOnce(2, "a", "b")
if str != "ab" && str != "ba" {
fmt.Println("6 failed", str)
}
if RandomStringAtLeastOnce(1, "a", "b") != "a" {
fmt.Println("7 failed")
}
str = RandomStringAtLeastOnce(7)
if len(str) != 7 {
fmt.Println("8 failed")
}
// Output:
//
}
func ExampleRandomStringWithTimestamp() {
t := time.Now().Unix()
rstr := RandomStringWithTimestamp(17, t)
date, str := ParseRandomStringWithTimestamp(rstr)
if t != date || str != rstr[RandomStringWithTimestampTimeLength:] {
fmt.Printf("before [%d] [%s] after [%d][%s]\n", t, rstr, date, str)
}
// Output:
//
t := time.Now().Unix()
rstr := RandomStringWithTimestamp(17, t)
date, str := ParseRandomStringWithTimestamp(rstr)
if t != date || str != rstr[RandomStringWithTimestampTimeLength:] {
fmt.Printf("before [%d] [%s] after [%d][%s]\n", t, rstr, date, str)
}
// Output:
//
}

166
sha1.go
View File

@ -1,151 +1,151 @@
package util
import (
"crypto/sha1"
"encoding/hex"
"errors"
"hash"
"io"
"os"
"path/filepath"
"strings"
"crypto/sha1"
"encoding/hex"
"errors"
"hash"
"io"
"os"
"path/filepath"
"strings"
)
const SHA1ResultLength = 20
type SHA1Result struct {
result [SHA1ResultLength]byte
err error
result [SHA1ResultLength]byte
err error
}
func (s *SHA1Result) Array() [SHA1ResultLength]byte {
return s.result
return s.result
}
func (s *SHA1Result) Slice() []byte {
return s.result[:]
return s.result[:]
}
func (s *SHA1Result) Upper() string {
return strings.ToUpper(hex.EncodeToString(s.result[:]))
return strings.ToUpper(hex.EncodeToString(s.result[:]))
}
func (s *SHA1Result) Lower() string {
return strings.ToLower(hex.EncodeToString(s.result[:]))
return strings.ToLower(hex.EncodeToString(s.result[:]))
}
func (s *SHA1Result) Error() error {
return s.err
return s.err
}
func NewSHA1Result(result []byte, err error) *SHA1Result {
res := &SHA1Result{
result: [SHA1ResultLength]byte{},
err: err,
}
copy(res.result[:], result)
return res
res := &SHA1Result{
result: [SHA1ResultLength]byte{},
err: err,
}
copy(res.result[:], result)
return res
}
type SHA1 struct{}
func NewSHA1() *SHA1 {
return &SHA1{}
return &SHA1{}
}
func (s *SHA1) FromReader(r io.Reader) *SHA1Result {
ha := sha1.New()
if _, err := io.Copy(ha, r); err != nil {
return NewSHA1Result(nil, err)
}
hashInBytes := ha.Sum(nil)
if len(hashInBytes) != SHA1ResultLength {
return NewSHA1Result(nil, errors.New("wrong length"))
}
return NewSHA1Result(hashInBytes, nil)
ha := sha1.New()
if _, err := io.Copy(ha, r); err != nil {
return NewSHA1Result(nil, err)
}
hashInBytes := ha.Sum(nil)
if len(hashInBytes) != SHA1ResultLength {
return NewSHA1Result(nil, errors.New("wrong length"))
}
return NewSHA1Result(hashInBytes, nil)
}
func (s *SHA1) FromFile(filename string) *SHA1Result {
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewSHA1Result(nil, err)
}
defer func() {
_ = file.Close()
}()
return s.FromReader(file)
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewSHA1Result(nil, err)
}
defer func() {
_ = file.Close()
}()
return s.FromReader(file)
}
func (s *SHA1) FromReaderChunk(r io.Reader, chunksize int) *SHA1Result {
buf := make([]byte, chunksize)
s1 := sha1.New()
var n int
var err error
for {
n, err = r.Read(buf)
if err != nil {
if err != io.EOF {
return NewSHA1Result(nil, err)
}
if n > 0 {
_, err = s1.Write(buf[:n])
if err != nil {
return NewSHA1Result(nil, err)
}
}
break
}
_, err = s1.Write(buf[:n])
if err != nil {
return NewSHA1Result(nil, err)
}
}
return NewSHA1Result(s1.Sum(nil), nil)
buf := make([]byte, chunksize)
s1 := sha1.New()
var n int
var err error
for {
n, err = r.Read(buf)
if err != nil {
if err != io.EOF {
return NewSHA1Result(nil, err)
}
if n > 0 {
_, err = s1.Write(buf[:n])
if err != nil {
return NewSHA1Result(nil, err)
}
}
break
}
_, err = s1.Write(buf[:n])
if err != nil {
return NewSHA1Result(nil, err)
}
}
return NewSHA1Result(s1.Sum(nil), nil)
}
func (s *SHA1) FromFileChunk(filename string, chunksize int) *SHA1Result {
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewSHA1Result(nil, err)
}
defer func() {
_ = file.Close()
}()
return s.FromReaderChunk(file, chunksize)
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewSHA1Result(nil, err)
}
defer func() {
_ = file.Close()
}()
return s.FromReaderChunk(file, chunksize)
}
func (s *SHA1) FromBytes(b []byte) *SHA1Result {
res := sha1.Sum(b)
return NewSHA1Result(res[:], nil)
res := sha1.Sum(b)
return NewSHA1Result(res[:], nil)
}
func (s *SHA1) FromString(str string) *SHA1Result {
res := sha1.Sum([]byte(str))
return NewSHA1Result(res[:], nil)
res := sha1.Sum([]byte(str))
return NewSHA1Result(res[:], nil)
}
type SHA1Pip struct {
sha1 hash.Hash
sha1 hash.Hash
}
func NewSHA1Pip() *SHA1Pip {
return &SHA1Pip{sha1: sha1.New()}
return &SHA1Pip{sha1: sha1.New()}
}
func (s *SHA1Pip) Write(data []byte) (n int, err error) {
return s.sha1.Write(data)
return s.sha1.Write(data)
}
func (s *SHA1Pip) WriteBytes(data []byte) error {
_, err := s.Write(data)
return err
_, err := s.Write(data)
return err
}
func (s *SHA1Pip) WriteString(data string) error {
_, err := s.Write([]byte(data))
return err
_, err := s.Write([]byte(data))
return err
}
func (s *SHA1Pip) Result() *SHA1Result {
return NewSHA1Result(s.sha1.Sum(nil), nil)
return NewSHA1Result(s.sha1.Sum(nil), nil)
}

View File

@ -1,167 +1,167 @@
package util
import (
"bytes"
"encoding/hex"
"fmt"
"io"
"strings"
"testing"
"bytes"
"encoding/hex"
"fmt"
"io"
"strings"
"testing"
)
func TestSHA1(t *testing.T) {
// dd if=/dev/zero of=testfile/testFile1 bs=4KB count=4
// sha1sum testFile1
const fileSHA1 = "f710c36ffd8c1698f74532968865cf1e8c2d7b3e"
testString := "Akvicor"
testStringP1 := "Akv"
testStringP2 := "icor"
testSHA1 := "49296886bfedac0dd0399030bc0dbe12e5eed489"
testSHA1P1 := "0b4e8f1f52b4ae507d2683e760a168bbbd94eef4"
testBytes := []byte(testString)
testBytesP1 := []byte(testStringP1)
testBytesP2 := []byte(testStringP2)
fileSHA1Bytes, err := hex.DecodeString(fileSHA1)
if err != nil {
t.Errorf("fileSHA1Bytes: %v", err)
}
// test FromFile & SHA1Result
s1 := NewSHA1().FromFile("testfile/testFile1")
if s1.Error() != nil {
t.Errorf("FromFile failed: %v", s1.Error())
}
if s1.Lower() != fileSHA1 {
t.Errorf("FromFile failed: expected: [%s] got [%s]", fileSHA1, s1.Lower())
}
if s1.Upper() != strings.ToUpper(fileSHA1) {
t.Errorf("FromFile failed: expected: [%s] got [%s]", strings.ToUpper(fileSHA1), s1.Upper())
}
if !bytes.Equal(s1.Slice(), fileSHA1Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileSHA1Bytes, s1.Slice())
}
ay := s1.Array()
if !bytes.Equal(ay[:], fileSHA1Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileSHA1Bytes, ay)
}
// test FromFileChunk
s1 = NewSHA1().FromFileChunk("testfile/testFile1", 1024)
if s1.Error() != nil {
t.Errorf("FromFileChunk failed: %v", s1.Error())
}
if s1.Lower() != fileSHA1 {
t.Errorf("FromFileChunk failed: expected: [%s] got [%s]", fileSHA1, s1.Lower())
}
// test FromBytes
s1 = NewSHA1().FromBytes(testBytes)
if s1.Error() != nil {
t.Errorf("FromBytes failed: %v", s1.Error())
}
if s1.Lower() != testSHA1 {
t.Errorf("FromBytes failed: expected: [%s] got [%s]", testSHA1, s1.Lower())
}
// test FromString
s1 = NewSHA1().FromString(testString)
if s1.Error() != nil {
t.Errorf("FromString failed: %v", s1.Error())
}
if s1.Lower() != testSHA1 {
t.Errorf("FromString failed: expected: [%s] got [%s]", testSHA1, s1.Lower())
}
// test NewSHA1Pip.WriteBytes
mp := NewSHA1Pip()
err = mp.WriteBytes(testBytesP1)
if err != nil {
t.Errorf("NewSHA1Pip WriteBytes failed: %v", err)
}
err = mp.WriteBytes(testBytesP2)
if err != nil {
t.Errorf("NewSHA1Pip WriteBytes failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA1Pip WriteBytes failed: %v", s1.Error())
}
if s1.Lower() != testSHA1 {
t.Errorf("NewSHA1Pip WriteBytes failed: expected: [%s] got [%s]", testSHA1, s1.Lower())
}
// test NewSHA1Pip.WriteString
mp = NewSHA1Pip()
err = mp.WriteString(testStringP1)
if err != nil {
t.Errorf("NewSHA1Pip WriteString failed: %v", err)
}
err = mp.WriteString(testStringP2)
if err != nil {
t.Errorf("NewSHA1Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA1Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA1 {
t.Errorf("NewSHA1Pip WriteString failed: expected: [%s] got [%s]", testSHA1, s1.Lower())
}
// test NewSHA1Pip.Result
mp = NewSHA1Pip()
err = mp.WriteString(testStringP1)
if err != nil {
t.Errorf("NewSHA1Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA1Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA1P1 {
t.Errorf("NewSHA1Pip WriteString failed: expected: [%s] got [%s]", testSHA1P1, s1.Lower())
}
err = mp.WriteString(testStringP2)
if err != nil {
t.Errorf("NewSHA1Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA1Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA1 {
t.Errorf("NewSHA1Pip WriteString failed: expected: [%s] got [%s]", testSHA1, s1.Lower())
}
// dd if=/dev/zero of=testfile/testFile1 bs=4KB count=4
// sha1sum testFile1
const fileSHA1 = "f710c36ffd8c1698f74532968865cf1e8c2d7b3e"
testString := "Akvicor"
testStringP1 := "Akv"
testStringP2 := "icor"
testSHA1 := "49296886bfedac0dd0399030bc0dbe12e5eed489"
testSHA1P1 := "0b4e8f1f52b4ae507d2683e760a168bbbd94eef4"
testBytes := []byte(testString)
testBytesP1 := []byte(testStringP1)
testBytesP2 := []byte(testStringP2)
fileSHA1Bytes, err := hex.DecodeString(fileSHA1)
if err != nil {
t.Errorf("fileSHA1Bytes: %v", err)
}
// test FromFile & SHA1Result
s1 := NewSHA1().FromFile("testfile/testFile1")
if s1.Error() != nil {
t.Errorf("FromFile failed: %v", s1.Error())
}
if s1.Lower() != fileSHA1 {
t.Errorf("FromFile failed: expected: [%s] got [%s]", fileSHA1, s1.Lower())
}
if s1.Upper() != strings.ToUpper(fileSHA1) {
t.Errorf("FromFile failed: expected: [%s] got [%s]", strings.ToUpper(fileSHA1), s1.Upper())
}
if !bytes.Equal(s1.Slice(), fileSHA1Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileSHA1Bytes, s1.Slice())
}
ay := s1.Array()
if !bytes.Equal(ay[:], fileSHA1Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileSHA1Bytes, ay)
}
// test FromFileChunk
s1 = NewSHA1().FromFileChunk("testfile/testFile1", 1024)
if s1.Error() != nil {
t.Errorf("FromFileChunk failed: %v", s1.Error())
}
if s1.Lower() != fileSHA1 {
t.Errorf("FromFileChunk failed: expected: [%s] got [%s]", fileSHA1, s1.Lower())
}
// test FromBytes
s1 = NewSHA1().FromBytes(testBytes)
if s1.Error() != nil {
t.Errorf("FromBytes failed: %v", s1.Error())
}
if s1.Lower() != testSHA1 {
t.Errorf("FromBytes failed: expected: [%s] got [%s]", testSHA1, s1.Lower())
}
// test FromString
s1 = NewSHA1().FromString(testString)
if s1.Error() != nil {
t.Errorf("FromString failed: %v", s1.Error())
}
if s1.Lower() != testSHA1 {
t.Errorf("FromString failed: expected: [%s] got [%s]", testSHA1, s1.Lower())
}
// test NewSHA1Pip.WriteBytes
mp := NewSHA1Pip()
err = mp.WriteBytes(testBytesP1)
if err != nil {
t.Errorf("NewSHA1Pip WriteBytes failed: %v", err)
}
err = mp.WriteBytes(testBytesP2)
if err != nil {
t.Errorf("NewSHA1Pip WriteBytes failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA1Pip WriteBytes failed: %v", s1.Error())
}
if s1.Lower() != testSHA1 {
t.Errorf("NewSHA1Pip WriteBytes failed: expected: [%s] got [%s]", testSHA1, s1.Lower())
}
// test NewSHA1Pip.WriteString
mp = NewSHA1Pip()
err = mp.WriteString(testStringP1)
if err != nil {
t.Errorf("NewSHA1Pip WriteString failed: %v", err)
}
err = mp.WriteString(testStringP2)
if err != nil {
t.Errorf("NewSHA1Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA1Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA1 {
t.Errorf("NewSHA1Pip WriteString failed: expected: [%s] got [%s]", testSHA1, s1.Lower())
}
// test NewSHA1Pip.Result
mp = NewSHA1Pip()
err = mp.WriteString(testStringP1)
if err != nil {
t.Errorf("NewSHA1Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA1Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA1P1 {
t.Errorf("NewSHA1Pip WriteString failed: expected: [%s] got [%s]", testSHA1P1, s1.Lower())
}
err = mp.WriteString(testStringP2)
if err != nil {
t.Errorf("NewSHA1Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA1Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA1 {
t.Errorf("NewSHA1Pip WriteString failed: expected: [%s] got [%s]", testSHA1, s1.Lower())
}
}
func ExampleNewSHA1() {
s := NewSHA1()
res := s.FromString("Akvicor")
if res.Error() == nil {
fmt.Println(res.Lower())
fmt.Println(res.Upper())
fmt.Println(res.Slice())
}
// Output:
// 49296886bfedac0dd0399030bc0dbe12e5eed489
// 49296886BFEDAC0DD0399030BC0DBE12E5EED489
// [73 41 104 134 191 237 172 13 208 57 144 48 188 13 190 18 229 238 212 137]
s := NewSHA1()
res := s.FromString("Akvicor")
if res.Error() == nil {
fmt.Println(res.Lower())
fmt.Println(res.Upper())
fmt.Println(res.Slice())
}
// Output:
// 49296886bfedac0dd0399030bc0dbe12e5eed489
// 49296886BFEDAC0DD0399030BC0DBE12E5EED489
// [73 41 104 134 191 237 172 13 208 57 144 48 188 13 190 18 229 238 212 137]
}
func ExampleNewSHA1Pip() {
sp := NewSHA1Pip()
_, err := io.WriteString(sp, "Akvicor")
if err != nil {
fmt.Println(err)
}
res := sp.Result()
if res.Error() == nil {
fmt.Println(res.Array())
fmt.Println(res.Slice())
}
// Output:
// [73 41 104 134 191 237 172 13 208 57 144 48 188 13 190 18 229 238 212 137]
// [73 41 104 134 191 237 172 13 208 57 144 48 188 13 190 18 229 238 212 137]
sp := NewSHA1Pip()
_, err := io.WriteString(sp, "Akvicor")
if err != nil {
fmt.Println(err)
}
res := sp.Result()
if res.Error() == nil {
fmt.Println(res.Array())
fmt.Println(res.Slice())
}
// Output:
// [73 41 104 134 191 237 172 13 208 57 144 48 188 13 190 18 229 238 212 137]
// [73 41 104 134 191 237 172 13 208 57 144 48 188 13 190 18 229 238 212 137]
}

166
sha256.go
View File

@ -1,151 +1,151 @@
package util
import (
"crypto/sha256"
"encoding/hex"
"errors"
"hash"
"io"
"os"
"path/filepath"
"strings"
"crypto/sha256"
"encoding/hex"
"errors"
"hash"
"io"
"os"
"path/filepath"
"strings"
)
const SHA256ResultLength = 32
type SHA256Result struct {
result [SHA256ResultLength]byte
err error
result [SHA256ResultLength]byte
err error
}
func (s *SHA256Result) Array() [SHA256ResultLength]byte {
return s.result
return s.result
}
func (s *SHA256Result) Slice() []byte {
return s.result[:]
return s.result[:]
}
func (s *SHA256Result) Upper() string {
return strings.ToUpper(hex.EncodeToString(s.result[:]))
return strings.ToUpper(hex.EncodeToString(s.result[:]))
}
func (s *SHA256Result) Lower() string {
return strings.ToLower(hex.EncodeToString(s.result[:]))
return strings.ToLower(hex.EncodeToString(s.result[:]))
}
func (s *SHA256Result) Error() error {
return s.err
return s.err
}
func NewSHA256Result(result []byte, err error) *SHA256Result {
res := &SHA256Result{
result: [SHA256ResultLength]byte{},
err: err,
}
copy(res.result[:], result)
return res
res := &SHA256Result{
result: [SHA256ResultLength]byte{},
err: err,
}
copy(res.result[:], result)
return res
}
type SHA256 struct{}
func NewSHA256() *SHA256 {
return &SHA256{}
return &SHA256{}
}
func (s *SHA256) FromReader(r io.Reader) *SHA256Result {
ha := sha256.New()
if _, err := io.Copy(ha, r); err != nil {
return NewSHA256Result(nil, err)
}
hashInBytes := ha.Sum(nil)
if len(hashInBytes) != SHA256ResultLength {
return NewSHA256Result(nil, errors.New("wrong length"))
}
return NewSHA256Result(hashInBytes, nil)
ha := sha256.New()
if _, err := io.Copy(ha, r); err != nil {
return NewSHA256Result(nil, err)
}
hashInBytes := ha.Sum(nil)
if len(hashInBytes) != SHA256ResultLength {
return NewSHA256Result(nil, errors.New("wrong length"))
}
return NewSHA256Result(hashInBytes, nil)
}
func (s *SHA256) FromFile(filename string) *SHA256Result {
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewSHA256Result(nil, err)
}
defer func() {
_ = file.Close()
}()
return s.FromReader(file)
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewSHA256Result(nil, err)
}
defer func() {
_ = file.Close()
}()
return s.FromReader(file)
}
func (s *SHA256) FromReaderChunk(r io.Reader, chunksize int) *SHA256Result {
buf := make([]byte, chunksize)
s1 := sha256.New()
var n int
var err error
for {
n, err = r.Read(buf)
if err != nil {
if err != io.EOF {
return NewSHA256Result(nil, err)
}
if n > 0 {
_, err = s1.Write(buf[:n])
if err != nil {
return NewSHA256Result(nil, err)
}
}
break
}
_, err = s1.Write(buf[:n])
if err != nil {
return NewSHA256Result(nil, err)
}
}
return NewSHA256Result(s1.Sum(nil), nil)
buf := make([]byte, chunksize)
s1 := sha256.New()
var n int
var err error
for {
n, err = r.Read(buf)
if err != nil {
if err != io.EOF {
return NewSHA256Result(nil, err)
}
if n > 0 {
_, err = s1.Write(buf[:n])
if err != nil {
return NewSHA256Result(nil, err)
}
}
break
}
_, err = s1.Write(buf[:n])
if err != nil {
return NewSHA256Result(nil, err)
}
}
return NewSHA256Result(s1.Sum(nil), nil)
}
func (s *SHA256) FromFileChunk(filename string, chunksize int) *SHA256Result {
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewSHA256Result(nil, err)
}
defer func() {
_ = file.Close()
}()
return s.FromReaderChunk(file, chunksize)
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewSHA256Result(nil, err)
}
defer func() {
_ = file.Close()
}()
return s.FromReaderChunk(file, chunksize)
}
func (s *SHA256) FromBytes(b []byte) *SHA256Result {
res := sha256.Sum256(b)
return NewSHA256Result(res[:], nil)
res := sha256.Sum256(b)
return NewSHA256Result(res[:], nil)
}
func (s *SHA256) FromString(str string) *SHA256Result {
res := sha256.Sum256([]byte(str))
return NewSHA256Result(res[:], nil)
res := sha256.Sum256([]byte(str))
return NewSHA256Result(res[:], nil)
}
type SHA256Pip struct {
sha256 hash.Hash
sha256 hash.Hash
}
func NewSHA256Pip() *SHA256Pip {
return &SHA256Pip{sha256: sha256.New()}
return &SHA256Pip{sha256: sha256.New()}
}
func (s *SHA256Pip) Write(data []byte) (n int, err error) {
return s.sha256.Write(data)
return s.sha256.Write(data)
}
func (s *SHA256Pip) WriteBytes(data []byte) error {
_, err := s.Write(data)
return err
_, err := s.Write(data)
return err
}
func (s *SHA256Pip) WriteString(data string) error {
_, err := s.Write([]byte(data))
return err
_, err := s.Write([]byte(data))
return err
}
func (s *SHA256Pip) Result() *SHA256Result {
return NewSHA256Result(s.sha256.Sum(nil), nil)
return NewSHA256Result(s.sha256.Sum(nil), nil)
}

View File

@ -1,167 +1,167 @@
package util
import (
"bytes"
"encoding/hex"
"fmt"
"io"
"strings"
"testing"
"bytes"
"encoding/hex"
"fmt"
"io"
"strings"
"testing"
)
func TestSHA256(t *testing.T) {
// dd if=/dev/zero of=testfile/testFile1 bs=4KB count=4
// sha256sum testFile1
const fileSHA256 = "f85f2c34eb2843d2aa5951ee6e8e76985655b2e3ae2cbdd76bdfd654ecf19997"
testString := "Akvicor"
testStringP1 := "Akv"
testStringP2 := "icor"
testSHA256 := "36acc0924a190c77386cd819a3bff60251345e8654399f68e8b740a1afa62ff5"
testSHA256P1 := "5a01f2f1bd960f10e647fb9c78797836a9774683469ef759c303cd2934548563"
testBytes := []byte(testString)
testBytesP1 := []byte(testStringP1)
testBytesP2 := []byte(testStringP2)
fileSHA256Bytes, err := hex.DecodeString(fileSHA256)
if err != nil {
t.Errorf("fileSHA256Bytes: %v", err)
}
// test FromFile & SHA256Result
s1 := NewSHA256().FromFile("testfile/testFile1")
if s1.Error() != nil {
t.Errorf("FromFile failed: %v", s1.Error())
}
if s1.Lower() != fileSHA256 {
t.Errorf("FromFile failed: expected: [%s] got [%s]", fileSHA256, s1.Lower())
}
if s1.Upper() != strings.ToUpper(fileSHA256) {
t.Errorf("FromFile failed: expected: [%s] got [%s]", strings.ToUpper(fileSHA256), s1.Upper())
}
if !bytes.Equal(s1.Slice(), fileSHA256Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileSHA256Bytes, s1.Slice())
}
ay := s1.Array()
if !bytes.Equal(ay[:], fileSHA256Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileSHA256Bytes, ay)
}
// test FromFileChunk
s1 = NewSHA256().FromFileChunk("testfile/testFile1", 1024)
if s1.Error() != nil {
t.Errorf("FromFileChunk failed: %v", s1.Error())
}
if s1.Lower() != fileSHA256 {
t.Errorf("FromFileChunk failed: expected: [%s] got [%s]", fileSHA256, s1.Lower())
}
// test FromBytes
s1 = NewSHA256().FromBytes(testBytes)
if s1.Error() != nil {
t.Errorf("FromBytes failed: %v", s1.Error())
}
if s1.Lower() != testSHA256 {
t.Errorf("FromBytes failed: expected: [%s] got [%s]", testSHA256, s1.Lower())
}
// test FromString
s1 = NewSHA256().FromString(testString)
if s1.Error() != nil {
t.Errorf("FromString failed: %v", s1.Error())
}
if s1.Lower() != testSHA256 {
t.Errorf("FromString failed: expected: [%s] got [%s]", testSHA256, s1.Lower())
}
// test NewSHA256Pip.WriteBytes
mp := NewSHA256Pip()
err = mp.WriteBytes(testBytesP1)
if err != nil {
t.Errorf("NewSHA256Pip WriteBytes failed: %v", err)
}
err = mp.WriteBytes(testBytesP2)
if err != nil {
t.Errorf("NewSHA256Pip WriteBytes failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA256Pip WriteBytes failed: %v", s1.Error())
}
if s1.Lower() != testSHA256 {
t.Errorf("NewSHA256Pip WriteBytes failed: expected: [%s] got [%s]", testSHA256, s1.Lower())
}
// test NewSHA256Pip.WriteString
mp = NewSHA256Pip()
err = mp.WriteString(testStringP1)
if err != nil {
t.Errorf("NewSHA256Pip WriteString failed: %v", err)
}
err = mp.WriteString(testStringP2)
if err != nil {
t.Errorf("NewSHA256Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA256Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA256 {
t.Errorf("NewSHA256Pip WriteString failed: expected: [%s] got [%s]", testSHA256, s1.Lower())
}
// test NewSHA256Pip.Result
mp = NewSHA256Pip()
err = mp.WriteString(testStringP1)
if err != nil {
t.Errorf("NewSHA256Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA256Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA256P1 {
t.Errorf("NewSHA256Pip WriteString failed: expected: [%s] got [%s]", testSHA256P1, s1.Lower())
}
err = mp.WriteString(testStringP2)
if err != nil {
t.Errorf("NewSHA256Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA256Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA256 {
t.Errorf("NewSHA256Pip WriteString failed: expected: [%s] got [%s]", testSHA256, s1.Lower())
}
// dd if=/dev/zero of=testfile/testFile1 bs=4KB count=4
// sha256sum testFile1
const fileSHA256 = "f85f2c34eb2843d2aa5951ee6e8e76985655b2e3ae2cbdd76bdfd654ecf19997"
testString := "Akvicor"
testStringP1 := "Akv"
testStringP2 := "icor"
testSHA256 := "36acc0924a190c77386cd819a3bff60251345e8654399f68e8b740a1afa62ff5"
testSHA256P1 := "5a01f2f1bd960f10e647fb9c78797836a9774683469ef759c303cd2934548563"
testBytes := []byte(testString)
testBytesP1 := []byte(testStringP1)
testBytesP2 := []byte(testStringP2)
fileSHA256Bytes, err := hex.DecodeString(fileSHA256)
if err != nil {
t.Errorf("fileSHA256Bytes: %v", err)
}
// test FromFile & SHA256Result
s1 := NewSHA256().FromFile("testfile/testFile1")
if s1.Error() != nil {
t.Errorf("FromFile failed: %v", s1.Error())
}
if s1.Lower() != fileSHA256 {
t.Errorf("FromFile failed: expected: [%s] got [%s]", fileSHA256, s1.Lower())
}
if s1.Upper() != strings.ToUpper(fileSHA256) {
t.Errorf("FromFile failed: expected: [%s] got [%s]", strings.ToUpper(fileSHA256), s1.Upper())
}
if !bytes.Equal(s1.Slice(), fileSHA256Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileSHA256Bytes, s1.Slice())
}
ay := s1.Array()
if !bytes.Equal(ay[:], fileSHA256Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileSHA256Bytes, ay)
}
// test FromFileChunk
s1 = NewSHA256().FromFileChunk("testfile/testFile1", 1024)
if s1.Error() != nil {
t.Errorf("FromFileChunk failed: %v", s1.Error())
}
if s1.Lower() != fileSHA256 {
t.Errorf("FromFileChunk failed: expected: [%s] got [%s]", fileSHA256, s1.Lower())
}
// test FromBytes
s1 = NewSHA256().FromBytes(testBytes)
if s1.Error() != nil {
t.Errorf("FromBytes failed: %v", s1.Error())
}
if s1.Lower() != testSHA256 {
t.Errorf("FromBytes failed: expected: [%s] got [%s]", testSHA256, s1.Lower())
}
// test FromString
s1 = NewSHA256().FromString(testString)
if s1.Error() != nil {
t.Errorf("FromString failed: %v", s1.Error())
}
if s1.Lower() != testSHA256 {
t.Errorf("FromString failed: expected: [%s] got [%s]", testSHA256, s1.Lower())
}
// test NewSHA256Pip.WriteBytes
mp := NewSHA256Pip()
err = mp.WriteBytes(testBytesP1)
if err != nil {
t.Errorf("NewSHA256Pip WriteBytes failed: %v", err)
}
err = mp.WriteBytes(testBytesP2)
if err != nil {
t.Errorf("NewSHA256Pip WriteBytes failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA256Pip WriteBytes failed: %v", s1.Error())
}
if s1.Lower() != testSHA256 {
t.Errorf("NewSHA256Pip WriteBytes failed: expected: [%s] got [%s]", testSHA256, s1.Lower())
}
// test NewSHA256Pip.WriteString
mp = NewSHA256Pip()
err = mp.WriteString(testStringP1)
if err != nil {
t.Errorf("NewSHA256Pip WriteString failed: %v", err)
}
err = mp.WriteString(testStringP2)
if err != nil {
t.Errorf("NewSHA256Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA256Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA256 {
t.Errorf("NewSHA256Pip WriteString failed: expected: [%s] got [%s]", testSHA256, s1.Lower())
}
// test NewSHA256Pip.Result
mp = NewSHA256Pip()
err = mp.WriteString(testStringP1)
if err != nil {
t.Errorf("NewSHA256Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA256Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA256P1 {
t.Errorf("NewSHA256Pip WriteString failed: expected: [%s] got [%s]", testSHA256P1, s1.Lower())
}
err = mp.WriteString(testStringP2)
if err != nil {
t.Errorf("NewSHA256Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA256Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA256 {
t.Errorf("NewSHA256Pip WriteString failed: expected: [%s] got [%s]", testSHA256, s1.Lower())
}
}
func ExampleNewSHA256() {
s := NewSHA256()
res := s.FromString("Akvicor")
if res.Error() == nil {
fmt.Println(res.Lower())
fmt.Println(res.Upper())
fmt.Println(res.Slice())
}
// Output:
// 36acc0924a190c77386cd819a3bff60251345e8654399f68e8b740a1afa62ff5
// 36ACC0924A190C77386CD819A3BFF60251345E8654399F68E8B740A1AFA62FF5
// [54 172 192 146 74 25 12 119 56 108 216 25 163 191 246 2 81 52 94 134 84 57 159 104 232 183 64 161 175 166 47 245]
s := NewSHA256()
res := s.FromString("Akvicor")
if res.Error() == nil {
fmt.Println(res.Lower())
fmt.Println(res.Upper())
fmt.Println(res.Slice())
}
// Output:
// 36acc0924a190c77386cd819a3bff60251345e8654399f68e8b740a1afa62ff5
// 36ACC0924A190C77386CD819A3BFF60251345E8654399F68E8B740A1AFA62FF5
// [54 172 192 146 74 25 12 119 56 108 216 25 163 191 246 2 81 52 94 134 84 57 159 104 232 183 64 161 175 166 47 245]
}
func ExampleNewSHA256Pip() {
sp := NewSHA256Pip()
_, err := io.WriteString(sp, "Akvicor")
if err != nil {
fmt.Println(err)
}
res := sp.Result()
if res.Error() == nil {
fmt.Println(res.Array())
fmt.Println(res.Slice())
}
// Output:
// [54 172 192 146 74 25 12 119 56 108 216 25 163 191 246 2 81 52 94 134 84 57 159 104 232 183 64 161 175 166 47 245]
// [54 172 192 146 74 25 12 119 56 108 216 25 163 191 246 2 81 52 94 134 84 57 159 104 232 183 64 161 175 166 47 245]
sp := NewSHA256Pip()
_, err := io.WriteString(sp, "Akvicor")
if err != nil {
fmt.Println(err)
}
res := sp.Result()
if res.Error() == nil {
fmt.Println(res.Array())
fmt.Println(res.Slice())
}
// Output:
// [54 172 192 146 74 25 12 119 56 108 216 25 163 191 246 2 81 52 94 134 84 57 159 104 232 183 64 161 175 166 47 245]
// [54 172 192 146 74 25 12 119 56 108 216 25 163 191 246 2 81 52 94 134 84 57 159 104 232 183 64 161 175 166 47 245]
}

166
sha512.go
View File

@ -1,151 +1,151 @@
package util
import (
"crypto/sha512"
"encoding/hex"
"errors"
"hash"
"io"
"os"
"path/filepath"
"strings"
"crypto/sha512"
"encoding/hex"
"errors"
"hash"
"io"
"os"
"path/filepath"
"strings"
)
const SHA512ResultLength = 64
type SHA512Result struct {
result [SHA512ResultLength]byte
err error
result [SHA512ResultLength]byte
err error
}
func (s *SHA512Result) Array() [SHA512ResultLength]byte {
return s.result
return s.result
}
func (s *SHA512Result) Slice() []byte {
return s.result[:]
return s.result[:]
}
func (s *SHA512Result) Upper() string {
return strings.ToUpper(hex.EncodeToString(s.result[:]))
return strings.ToUpper(hex.EncodeToString(s.result[:]))
}
func (s *SHA512Result) Lower() string {
return strings.ToLower(hex.EncodeToString(s.result[:]))
return strings.ToLower(hex.EncodeToString(s.result[:]))
}
func (s *SHA512Result) Error() error {
return s.err
return s.err
}
func NewSHA512Result(result []byte, err error) *SHA512Result {
res := &SHA512Result{
result: [SHA512ResultLength]byte{},
err: err,
}
copy(res.result[:], result)
return res
res := &SHA512Result{
result: [SHA512ResultLength]byte{},
err: err,
}
copy(res.result[:], result)
return res
}
type SHA512 struct{}
func NewSHA512() *SHA512 {
return &SHA512{}
return &SHA512{}
}
func (s *SHA512) FromReader(r io.Reader) *SHA512Result {
ha := sha512.New()
if _, err := io.Copy(ha, r); err != nil {
return NewSHA512Result(nil, err)
}
hashInBytes := ha.Sum(nil)
if len(hashInBytes) != SHA512ResultLength {
return NewSHA512Result(nil, errors.New("wrong length"))
}
return NewSHA512Result(hashInBytes, nil)
ha := sha512.New()
if _, err := io.Copy(ha, r); err != nil {
return NewSHA512Result(nil, err)
}
hashInBytes := ha.Sum(nil)
if len(hashInBytes) != SHA512ResultLength {
return NewSHA512Result(nil, errors.New("wrong length"))
}
return NewSHA512Result(hashInBytes, nil)
}
func (s *SHA512) FromFile(filename string) *SHA512Result {
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewSHA512Result(nil, err)
}
defer func() {
_ = file.Close()
}()
return s.FromReader(file)
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewSHA512Result(nil, err)
}
defer func() {
_ = file.Close()
}()
return s.FromReader(file)
}
func (s *SHA512) FromReaderChunk(r io.Reader, chunksize int) *SHA512Result {
buf := make([]byte, chunksize)
s1 := sha512.New()
var n int
var err error
for {
n, err = r.Read(buf)
if err != nil {
if err != io.EOF {
return NewSHA512Result(nil, err)
}
if n > 0 {
_, err = s1.Write(buf[:n])
if err != nil {
return NewSHA512Result(nil, err)
}
}
break
}
_, err = s1.Write(buf[:n])
if err != nil {
return NewSHA512Result(nil, err)
}
}
return NewSHA512Result(s1.Sum(nil), nil)
buf := make([]byte, chunksize)
s1 := sha512.New()
var n int
var err error
for {
n, err = r.Read(buf)
if err != nil {
if err != io.EOF {
return NewSHA512Result(nil, err)
}
if n > 0 {
_, err = s1.Write(buf[:n])
if err != nil {
return NewSHA512Result(nil, err)
}
}
break
}
_, err = s1.Write(buf[:n])
if err != nil {
return NewSHA512Result(nil, err)
}
}
return NewSHA512Result(s1.Sum(nil), nil)
}
func (s *SHA512) FromFileChunk(filename string, chunksize int) *SHA512Result {
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewSHA512Result(nil, err)
}
defer func() {
_ = file.Close()
}()
return s.FromReaderChunk(file, chunksize)
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return NewSHA512Result(nil, err)
}
defer func() {
_ = file.Close()
}()
return s.FromReaderChunk(file, chunksize)
}
func (s *SHA512) FromBytes(b []byte) *SHA512Result {
res := sha512.Sum512(b)
return NewSHA512Result(res[:], nil)
res := sha512.Sum512(b)
return NewSHA512Result(res[:], nil)
}
func (s *SHA512) FromString(str string) *SHA512Result {
res := sha512.Sum512([]byte(str))
return NewSHA512Result(res[:], nil)
res := sha512.Sum512([]byte(str))
return NewSHA512Result(res[:], nil)
}
type SHA512Pip struct {
sha512 hash.Hash
sha512 hash.Hash
}
func NewSHA512Pip() *SHA512Pip {
return &SHA512Pip{sha512: sha512.New()}
return &SHA512Pip{sha512: sha512.New()}
}
func (s *SHA512Pip) Write(data []byte) (n int, err error) {
return s.sha512.Write(data)
return s.sha512.Write(data)
}
func (s *SHA512Pip) WriteBytes(data []byte) error {
_, err := s.Write(data)
return err
_, err := s.Write(data)
return err
}
func (s *SHA512Pip) WriteString(data string) error {
_, err := s.Write([]byte(data))
return err
_, err := s.Write([]byte(data))
return err
}
func (s *SHA512Pip) Result() *SHA512Result {
return NewSHA512Result(s.sha512.Sum(nil), nil)
return NewSHA512Result(s.sha512.Sum(nil), nil)
}

View File

@ -1,167 +1,167 @@
package util
import (
"bytes"
"encoding/hex"
"fmt"
"io"
"strings"
"testing"
"bytes"
"encoding/hex"
"fmt"
"io"
"strings"
"testing"
)
func TestSHA512(t *testing.T) {
// dd if=/dev/zero of=testfile/testFile1 bs=4KB count=4
// sha512sum testFile1
const fileSHA512 = "88e09cee3dd9d332821e57e6f7f781eecac6b40207c92469631314220c59fb624170067159a34aa7bd614a1cff02e02a9b875a468c87ff6e01ee370fce9d736e"
testString := "Akvicor"
testStringP1 := "Akv"
testStringP2 := "icor"
testSHA512 := "6fdfb481af6573ac49d4031d22f0d73f0f24ea8cb113982593ec65ab085b0635b46d7683aa3f4ef36c2cb25a7bb8ba8cbae2fa3e9810d35b1c70a93f37586361"
testSHA512P1 := "3c7ec9519b880b2a6438dea41c4d49cb8761f167dadb237690799aae202852c688d7234f34fa8ff468b794cbfff542e5bd9c77a20f74db7aff7f0b716b49af9c"
testBytes := []byte(testString)
testBytesP1 := []byte(testStringP1)
testBytesP2 := []byte(testStringP2)
fileSHA512Bytes, err := hex.DecodeString(fileSHA512)
if err != nil {
t.Errorf("fileSHA512Bytes: %v", err)
}
// test FromFile & SHA512Result
s1 := NewSHA512().FromFile("testfile/testFile1")
if s1.Error() != nil {
t.Errorf("FromFile failed: %v", s1.Error())
}
if s1.Lower() != fileSHA512 {
t.Errorf("FromFile failed: expected: [%s] got [%s]", fileSHA512, s1.Lower())
}
if s1.Upper() != strings.ToUpper(fileSHA512) {
t.Errorf("FromFile failed: expected: [%s] got [%s]", strings.ToUpper(fileSHA512), s1.Upper())
}
if !bytes.Equal(s1.Slice(), fileSHA512Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileSHA512Bytes, s1.Slice())
}
ay := s1.Array()
if !bytes.Equal(ay[:], fileSHA512Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileSHA512Bytes, ay)
}
// test FromFileChunk
s1 = NewSHA512().FromFileChunk("testfile/testFile1", 1024)
if s1.Error() != nil {
t.Errorf("FromFileChunk failed: %v", s1.Error())
}
if s1.Lower() != fileSHA512 {
t.Errorf("FromFileChunk failed: expected: [%s] got [%s]", fileSHA512, s1.Lower())
}
// test FromBytes
s1 = NewSHA512().FromBytes(testBytes)
if s1.Error() != nil {
t.Errorf("FromBytes failed: %v", s1.Error())
}
if s1.Lower() != testSHA512 {
t.Errorf("FromBytes failed: expected: [%s] got [%s]", testSHA512, s1.Lower())
}
// test FromString
s1 = NewSHA512().FromString(testString)
if s1.Error() != nil {
t.Errorf("FromString failed: %v", s1.Error())
}
if s1.Lower() != testSHA512 {
t.Errorf("FromString failed: expected: [%s] got [%s]", testSHA512, s1.Lower())
}
// test NewSHA512Pip.WriteBytes
mp := NewSHA512Pip()
err = mp.WriteBytes(testBytesP1)
if err != nil {
t.Errorf("NewSHA512Pip WriteBytes failed: %v", err)
}
err = mp.WriteBytes(testBytesP2)
if err != nil {
t.Errorf("NewSHA512Pip WriteBytes failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA512Pip WriteBytes failed: %v", s1.Error())
}
if s1.Lower() != testSHA512 {
t.Errorf("NewSHA512Pip WriteBytes failed: expected: [%s] got [%s]", testSHA512, s1.Lower())
}
// test NewSHA512Pip.WriteString
mp = NewSHA512Pip()
err = mp.WriteString(testStringP1)
if err != nil {
t.Errorf("NewSHA512Pip WriteString failed: %v", err)
}
err = mp.WriteString(testStringP2)
if err != nil {
t.Errorf("NewSHA512Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA512Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA512 {
t.Errorf("NewSHA512Pip WriteString failed: expected: [%s] got [%s]", testSHA512, s1.Lower())
}
// test NewSHA512Pip.Result
mp = NewSHA512Pip()
err = mp.WriteString(testStringP1)
if err != nil {
t.Errorf("NewSHA512Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA512Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA512P1 {
t.Errorf("NewSHA512Pip WriteString failed: expected: [%s] got [%s]", testSHA512P1, s1.Lower())
}
err = mp.WriteString(testStringP2)
if err != nil {
t.Errorf("NewSHA512Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA512Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA512 {
t.Errorf("NewSHA512Pip WriteString failed: expected: [%s] got [%s]", testSHA512, s1.Lower())
}
// dd if=/dev/zero of=testfile/testFile1 bs=4KB count=4
// sha512sum testFile1
const fileSHA512 = "88e09cee3dd9d332821e57e6f7f781eecac6b40207c92469631314220c59fb624170067159a34aa7bd614a1cff02e02a9b875a468c87ff6e01ee370fce9d736e"
testString := "Akvicor"
testStringP1 := "Akv"
testStringP2 := "icor"
testSHA512 := "6fdfb481af6573ac49d4031d22f0d73f0f24ea8cb113982593ec65ab085b0635b46d7683aa3f4ef36c2cb25a7bb8ba8cbae2fa3e9810d35b1c70a93f37586361"
testSHA512P1 := "3c7ec9519b880b2a6438dea41c4d49cb8761f167dadb237690799aae202852c688d7234f34fa8ff468b794cbfff542e5bd9c77a20f74db7aff7f0b716b49af9c"
testBytes := []byte(testString)
testBytesP1 := []byte(testStringP1)
testBytesP2 := []byte(testStringP2)
fileSHA512Bytes, err := hex.DecodeString(fileSHA512)
if err != nil {
t.Errorf("fileSHA512Bytes: %v", err)
}
// test FromFile & SHA512Result
s1 := NewSHA512().FromFile("testfile/testFile1")
if s1.Error() != nil {
t.Errorf("FromFile failed: %v", s1.Error())
}
if s1.Lower() != fileSHA512 {
t.Errorf("FromFile failed: expected: [%s] got [%s]", fileSHA512, s1.Lower())
}
if s1.Upper() != strings.ToUpper(fileSHA512) {
t.Errorf("FromFile failed: expected: [%s] got [%s]", strings.ToUpper(fileSHA512), s1.Upper())
}
if !bytes.Equal(s1.Slice(), fileSHA512Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileSHA512Bytes, s1.Slice())
}
ay := s1.Array()
if !bytes.Equal(ay[:], fileSHA512Bytes) {
t.Errorf("FromFile failed: expected: [%v] got [%v]", fileSHA512Bytes, ay)
}
// test FromFileChunk
s1 = NewSHA512().FromFileChunk("testfile/testFile1", 1024)
if s1.Error() != nil {
t.Errorf("FromFileChunk failed: %v", s1.Error())
}
if s1.Lower() != fileSHA512 {
t.Errorf("FromFileChunk failed: expected: [%s] got [%s]", fileSHA512, s1.Lower())
}
// test FromBytes
s1 = NewSHA512().FromBytes(testBytes)
if s1.Error() != nil {
t.Errorf("FromBytes failed: %v", s1.Error())
}
if s1.Lower() != testSHA512 {
t.Errorf("FromBytes failed: expected: [%s] got [%s]", testSHA512, s1.Lower())
}
// test FromString
s1 = NewSHA512().FromString(testString)
if s1.Error() != nil {
t.Errorf("FromString failed: %v", s1.Error())
}
if s1.Lower() != testSHA512 {
t.Errorf("FromString failed: expected: [%s] got [%s]", testSHA512, s1.Lower())
}
// test NewSHA512Pip.WriteBytes
mp := NewSHA512Pip()
err = mp.WriteBytes(testBytesP1)
if err != nil {
t.Errorf("NewSHA512Pip WriteBytes failed: %v", err)
}
err = mp.WriteBytes(testBytesP2)
if err != nil {
t.Errorf("NewSHA512Pip WriteBytes failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA512Pip WriteBytes failed: %v", s1.Error())
}
if s1.Lower() != testSHA512 {
t.Errorf("NewSHA512Pip WriteBytes failed: expected: [%s] got [%s]", testSHA512, s1.Lower())
}
// test NewSHA512Pip.WriteString
mp = NewSHA512Pip()
err = mp.WriteString(testStringP1)
if err != nil {
t.Errorf("NewSHA512Pip WriteString failed: %v", err)
}
err = mp.WriteString(testStringP2)
if err != nil {
t.Errorf("NewSHA512Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA512Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA512 {
t.Errorf("NewSHA512Pip WriteString failed: expected: [%s] got [%s]", testSHA512, s1.Lower())
}
// test NewSHA512Pip.Result
mp = NewSHA512Pip()
err = mp.WriteString(testStringP1)
if err != nil {
t.Errorf("NewSHA512Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA512Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA512P1 {
t.Errorf("NewSHA512Pip WriteString failed: expected: [%s] got [%s]", testSHA512P1, s1.Lower())
}
err = mp.WriteString(testStringP2)
if err != nil {
t.Errorf("NewSHA512Pip WriteString failed: %v", err)
}
s1 = mp.Result()
if s1.Error() != nil {
t.Errorf("NewSHA512Pip WriteString failed: %v", s1.Error())
}
if s1.Lower() != testSHA512 {
t.Errorf("NewSHA512Pip WriteString failed: expected: [%s] got [%s]", testSHA512, s1.Lower())
}
}
func ExampleNewSHA512() {
s := NewSHA512()
res := s.FromString("Akvicor")
if res.Error() == nil {
fmt.Println(res.Lower())
fmt.Println(res.Upper())
fmt.Println(res.Slice())
}
// Output:
// 6fdfb481af6573ac49d4031d22f0d73f0f24ea8cb113982593ec65ab085b0635b46d7683aa3f4ef36c2cb25a7bb8ba8cbae2fa3e9810d35b1c70a93f37586361
// 6FDFB481AF6573AC49D4031D22F0D73F0F24EA8CB113982593EC65AB085B0635B46D7683AA3F4EF36C2CB25A7BB8BA8CBAE2FA3E9810D35B1C70A93F37586361
// [111 223 180 129 175 101 115 172 73 212 3 29 34 240 215 63 15 36 234 140 177 19 152 37 147 236 101 171 8 91 6 53 180 109 118 131 170 63 78 243 108 44 178 90 123 184 186 140 186 226 250 62 152 16 211 91 28 112 169 63 55 88 99 97]
s := NewSHA512()
res := s.FromString("Akvicor")
if res.Error() == nil {
fmt.Println(res.Lower())
fmt.Println(res.Upper())
fmt.Println(res.Slice())
}
// Output:
// 6fdfb481af6573ac49d4031d22f0d73f0f24ea8cb113982593ec65ab085b0635b46d7683aa3f4ef36c2cb25a7bb8ba8cbae2fa3e9810d35b1c70a93f37586361
// 6FDFB481AF6573AC49D4031D22F0D73F0F24EA8CB113982593EC65AB085B0635B46D7683AA3F4EF36C2CB25A7BB8BA8CBAE2FA3E9810D35B1C70A93F37586361
// [111 223 180 129 175 101 115 172 73 212 3 29 34 240 215 63 15 36 234 140 177 19 152 37 147 236 101 171 8 91 6 53 180 109 118 131 170 63 78 243 108 44 178 90 123 184 186 140 186 226 250 62 152 16 211 91 28 112 169 63 55 88 99 97]
}
func ExampleNewSHA512Pip() {
sp := NewSHA512Pip()
_, err := io.WriteString(sp, "Akvicor")
if err != nil {
fmt.Println(err)
}
res := sp.Result()
if res.Error() == nil {
fmt.Println(res.Array())
fmt.Println(res.Slice())
}
// Output:
// [111 223 180 129 175 101 115 172 73 212 3 29 34 240 215 63 15 36 234 140 177 19 152 37 147 236 101 171 8 91 6 53 180 109 118 131 170 63 78 243 108 44 178 90 123 184 186 140 186 226 250 62 152 16 211 91 28 112 169 63 55 88 99 97]
// [111 223 180 129 175 101 115 172 73 212 3 29 34 240 215 63 15 36 234 140 177 19 152 37 147 236 101 171 8 91 6 53 180 109 118 131 170 63 78 243 108 44 178 90 123 184 186 140 186 226 250 62 152 16 211 91 28 112 169 63 55 88 99 97]
sp := NewSHA512Pip()
_, err := io.WriteString(sp, "Akvicor")
if err != nil {
fmt.Println(err)
}
res := sp.Result()
if res.Error() == nil {
fmt.Println(res.Array())
fmt.Println(res.Slice())
}
// Output:
// [111 223 180 129 175 101 115 172 73 212 3 29 34 240 215 63 15 36 234 140 177 19 152 37 147 236 101 171 8 91 6 53 180 109 118 131 170 63 78 243 108 44 178 90 123 184 186 140 186 226 250 62 152 16 211 91 28 112 169 63 55 88 99 97]
// [111 223 180 129 175 101 115 172 73 212 3 29 34 240 215 63 15 36 234 140 177 19 152 37 147 236 101 171 8 91 6 53 180 109 118 131 170 63 78 243 108 44 178 90 123 184 186 140 186 226 250 62 152 16 211 91 28 112 169 63 55 88 99 97]
}

102
time.go
View File

@ -1,99 +1,99 @@
package util
import (
"fmt"
"strconv"
"time"
"fmt"
"strconv"
"time"
)
const TimeFormatLayout = "2006-01-02 15:04:05"
func TimeNowFormat() string {
return time.Now().Format(TimeFormatLayout)
return time.Now().Format(TimeFormatLayout)
}
func TimeNowToBase36(length ...int) string {
if len(length) > 0 {
return fmt.Sprintf("%0*s", length[0], strconv.FormatInt(time.Now().Unix(), 36))
}
return strconv.FormatInt(time.Now().Unix(), 36)
if len(length) > 0 {
return fmt.Sprintf("%0*s", length[0], strconv.FormatInt(time.Now().Unix(), 36))
}
return strconv.FormatInt(time.Now().Unix(), 36)
}
func TimeUnixToFormat(unix int64) string {
return time.Unix(unix, 0).Format(TimeFormatLayout)
return time.Unix(unix, 0).Format(TimeFormatLayout)
}
func TimeUnixToBase36(unix int64, length ...int) string {
if len(length) > 0 {
return fmt.Sprintf("%0*s", length[0], strconv.FormatInt(unix, 36))
}
return strconv.FormatInt(unix, 36)
if len(length) > 0 {
return fmt.Sprintf("%0*s", length[0], strconv.FormatInt(unix, 36))
}
return strconv.FormatInt(unix, 36)
}
func TimeBase36ToUnix(t string) int64 {
date, err := strconv.ParseInt(t, 36, 64)
if err != nil {
return 0
}
return date
date, err := strconv.ParseInt(t, 36, 64)
if err != nil {
return 0
}
return date
}
func YearBetweenTwoDate(t1, t2 time.Time) int64 {
return int64(t1.Year() - t2.Year())
return int64(t1.Year() - t2.Year())
}
func YearBetweenTwoTime(t1, t2 time.Time) int64 {
f := int64(1)
if t1.Before(t2) {
f = -1
t1, t2 = t2, t1
}
y := int64(t1.Year() - t2.Year())
t1 = t1.AddDate(-t1.Year(), 0, 0)
t2 = t2.AddDate(-t2.Year(), 0, 0)
if t1.Before(t2) {
return f * (y - 1)
}
return f * y
f := int64(1)
if t1.Before(t2) {
f = -1
t1, t2 = t2, t1
}
y := int64(t1.Year() - t2.Year())
t1 = t1.AddDate(-t1.Year(), 0, 0)
t2 = t2.AddDate(-t2.Year(), 0, 0)
if t1.Before(t2) {
return f * (y - 1)
}
return f * y
}
func MonthBetweenTwoDate(t1, t2 time.Time) int64 {
return 12*int64(t1.Year()-t2.Year()) + int64(t1.Month()-t2.Month())
return 12*int64(t1.Year()-t2.Year()) + int64(t1.Month()-t2.Month())
}
func MonthBetweenTwoTime(t1, t2 time.Time) int64 {
f := int64(1)
if t1.Before(t2) {
f = -1
t1, t2 = t2, t1
}
m := 12*int64(t1.Year()-t2.Year()) + int64(t1.Month()-t2.Month())
t1 = t1.AddDate(-t1.Year(), -int(t1.Month()-1), 0)
t2 = t2.AddDate(-t2.Year(), -int(t2.Month()-1), 0)
if t1.Before(t2) {
return f * (m - 1)
}
return f * m
f := int64(1)
if t1.Before(t2) {
f = -1
t1, t2 = t2, t1
}
m := 12*int64(t1.Year()-t2.Year()) + int64(t1.Month()-t2.Month())
t1 = t1.AddDate(-t1.Year(), -int(t1.Month()-1), 0)
t2 = t2.AddDate(-t2.Year(), -int(t2.Month()-1), 0)
if t1.Before(t2) {
return f * (m - 1)
}
return f * m
}
func DayBetweenTwoDate(t1, t2 time.Time) int64 {
t1 = time.Date(t1.Year(), t1.Month(), t1.Day(), 0, 0, 0, 0, time.Local)
t2 = time.Date(t2.Year(), t2.Month(), t2.Day(), 0, 0, 0, 0, time.Local)
return int64(t1.Sub(t2).Hours() / 24)
t1 = time.Date(t1.Year(), t1.Month(), t1.Day(), 0, 0, 0, 0, time.Local)
t2 = time.Date(t2.Year(), t2.Month(), t2.Day(), 0, 0, 0, 0, time.Local)
return int64(t1.Sub(t2).Hours() / 24)
}
func DayBetweenTwoTime(t1, t2 time.Time) int64 {
return int64(t1.Sub(t2).Hours() / 24)
return int64(t1.Sub(t2).Hours() / 24)
}
func HourBetweenTwoTime(t1, t2 time.Time) int64 {
return int64(t1.Sub(t2).Hours())
return int64(t1.Sub(t2).Hours())
}
func MinuteBetweenTwoTime(t1, t2 time.Time) int64 {
return int64(t1.Sub(t2).Minutes())
return int64(t1.Sub(t2).Minutes())
}
func SecondBetweenTwoTime(t1, t2 time.Time) int64 {
return int64(t1.Sub(t2).Seconds())
return int64(t1.Sub(t2).Seconds())
}

View File

@ -1,243 +1,243 @@
package util
import (
"fmt"
"time"
"fmt"
"time"
)
func ExampleTimeNowFormat() {
t := TimeNowFormat()
if len(t) != 19 {
fmt.Println(t)
}
// Output:
//
t := TimeNowFormat()
if len(t) != 19 {
fmt.Println(t)
}
// Output:
//
}
func ExampleTimeUnixToFormat() {
t := TimeUnixToFormat(1705675065)
fmt.Println(t)
// Output:
// 2024-01-19 22:37:45
t := TimeUnixToFormat(1705675065)
fmt.Println(t)
// Output:
// 2024-01-19 22:37:45
}
func ExampleTimeNowToBase36() {
s := TimeNowToBase36()
if len(s) < 1 {
fmt.Println(s)
}
s = TimeNowToBase36(8)
if len(s) != 8 {
fmt.Println(s)
}
// Output:
//
s := TimeNowToBase36()
if len(s) < 1 {
fmt.Println(s)
}
s = TimeNowToBase36(8)
if len(s) != 8 {
fmt.Println(s)
}
// Output:
//
}
func ExampleTimeUnixToBase36() {
s := TimeUnixToBase36(1705675065)
fmt.Println(s)
s = TimeUnixToBase36(1705675065, 8)
fmt.Println(s)
// Output:
// s7ijax
// 00s7ijax
s := TimeUnixToBase36(1705675065)
fmt.Println(s)
s = TimeUnixToBase36(1705675065, 8)
fmt.Println(s)
// Output:
// s7ijax
// 00s7ijax
}
func ExampleTimeBase36ToUnix() {
t := TimeBase36ToUnix("s7ijax")
fmt.Println(t)
t = TimeBase36ToUnix("00s7ijax")
fmt.Println(t)
// Output:
// 1705675065
// 1705675065
t := TimeBase36ToUnix("s7ijax")
fmt.Println(t)
t = TimeBase36ToUnix("00s7ijax")
fmt.Println(t)
// Output:
// 1705675065
// 1705675065
}
func ExampleYearBetweenTwoDate() {
t1 := int64(1739929126)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(YearBetweenTwoDate(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(YearBetweenTwoDate(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(YearBetweenTwoDate(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2025-02-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 1
// -1
t1 := int64(1739929126)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(YearBetweenTwoDate(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(YearBetweenTwoDate(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(YearBetweenTwoDate(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2025-02-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 1
// -1
}
func ExampleYearBetweenTwoTime() {
t1 := int64(1739929126)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(YearBetweenTwoTime(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(YearBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(YearBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
t1 = int64(1737211064)
t2 = int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(YearBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(YearBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
t1 = int64(1737211066)
t2 = int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(YearBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(YearBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2025-02-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 1
// -1
// 2025-01-18 22:37:44 -> 2024-01-18 22:37:45
// 0
// 0
// 2025-01-18 22:37:46 -> 2024-01-18 22:37:45
// 1
// -1
t1 := int64(1739929126)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(YearBetweenTwoTime(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(YearBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(YearBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
t1 = int64(1737211064)
t2 = int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(YearBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(YearBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
t1 = int64(1737211066)
t2 = int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(YearBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(YearBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2025-02-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 1
// -1
// 2025-01-18 22:37:44 -> 2024-01-18 22:37:45
// 0
// 0
// 2025-01-18 22:37:46 -> 2024-01-18 22:37:45
// 1
// -1
}
func ExampleMonthBetweenTwoDate() {
t1 := int64(1739929126)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(MonthBetweenTwoDate(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(MonthBetweenTwoDate(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(MonthBetweenTwoDate(time.Unix(t2, 0), time.Unix(t1, 0)))
t1 = int64(1737211064)
t2 = int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(MonthBetweenTwoDate(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(MonthBetweenTwoDate(time.Unix(t2, 0), time.Unix(t1, 0)))
t1 = int64(1737211066)
t2 = int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(MonthBetweenTwoDate(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(MonthBetweenTwoDate(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2025-02-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 13
// -13
// 2025-01-18 22:37:44 -> 2024-01-18 22:37:45
// 12
// -12
// 2025-01-18 22:37:46 -> 2024-01-18 22:37:45
// 12
// -12
t1 := int64(1739929126)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(MonthBetweenTwoDate(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(MonthBetweenTwoDate(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(MonthBetweenTwoDate(time.Unix(t2, 0), time.Unix(t1, 0)))
t1 = int64(1737211064)
t2 = int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(MonthBetweenTwoDate(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(MonthBetweenTwoDate(time.Unix(t2, 0), time.Unix(t1, 0)))
t1 = int64(1737211066)
t2 = int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(MonthBetweenTwoDate(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(MonthBetweenTwoDate(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2025-02-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 13
// -13
// 2025-01-18 22:37:44 -> 2024-01-18 22:37:45
// 12
// -12
// 2025-01-18 22:37:46 -> 2024-01-18 22:37:45
// 12
// -12
}
func ExampleMonthBetweenTwoTime() {
t1 := int64(1739929126)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(MonthBetweenTwoTime(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(MonthBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(MonthBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
t1 = int64(1737211064)
t2 = int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(MonthBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(MonthBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
t1 = int64(1737211066)
t2 = int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(MonthBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(MonthBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2025-02-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 13
// -13
// 2025-01-18 22:37:44 -> 2024-01-18 22:37:45
// 11
// -11
// 2025-01-18 22:37:46 -> 2024-01-18 22:37:45
// 12
// -12
t1 := int64(1739929126)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(MonthBetweenTwoTime(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(MonthBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(MonthBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
t1 = int64(1737211064)
t2 = int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(MonthBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(MonthBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
t1 = int64(1737211066)
t2 = int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(MonthBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(MonthBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2025-02-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 13
// -13
// 2025-01-18 22:37:44 -> 2024-01-18 22:37:45
// 11
// -11
// 2025-01-18 22:37:46 -> 2024-01-18 22:37:45
// 12
// -12
}
func ExampleDayBetweenTwoDate() {
t1 := int64(1705628326)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(DayBetweenTwoDate(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(DayBetweenTwoDate(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(DayBetweenTwoDate(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2024-01-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 1
// -1
t1 := int64(1705628326)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(DayBetweenTwoDate(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(DayBetweenTwoDate(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(DayBetweenTwoDate(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2024-01-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 1
// -1
}
func ExampleDayBetweenTwoTime() {
t1 := int64(1705628326)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(DayBetweenTwoTime(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(DayBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(DayBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2024-01-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 0
// 0
t1 := int64(1705628326)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(DayBetweenTwoTime(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(DayBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(DayBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2024-01-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 0
// 0
}
func ExampleHourBetweenTwoTime() {
t1 := int64(1705628326)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(HourBetweenTwoTime(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(HourBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(HourBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2024-01-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 11
// -11
t1 := int64(1705628326)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(HourBetweenTwoTime(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(HourBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(HourBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2024-01-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 11
// -11
}
func ExampleMinuteBetweenTwoTime() {
t1 := int64(1705628326)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(MinuteBetweenTwoTime(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(MinuteBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(MinuteBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2024-01-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 661
// -661
t1 := int64(1705628326)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(MinuteBetweenTwoTime(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(MinuteBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(MinuteBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2024-01-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 661
// -661
}
func ExampleSecondBetweenTwoTime() {
t1 := int64(1705628326)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(SecondBetweenTwoTime(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(SecondBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(SecondBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2024-01-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 39661
// -39661
t1 := int64(1705628326)
t2 := int64(1705588665)
fmt.Printf("%s -> %s\n", TimeUnixToFormat(t1), TimeUnixToFormat(t2))
fmt.Println(SecondBetweenTwoTime(time.Unix(t1, 0), time.Unix(t1, 0)))
fmt.Println(SecondBetweenTwoTime(time.Unix(t1, 0), time.Unix(t2, 0)))
fmt.Println(SecondBetweenTwoTime(time.Unix(t2, 0), time.Unix(t1, 0)))
// Output:
// 2024-01-19 09:38:46 -> 2024-01-18 22:37:45
// 0
// 39661
// -39661
}