strutils

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 26, 2018 License: MIT Imports: 18 Imported by: 0

README

Just! a String Processing Library for Go-lang

Just Several methods for helping processing/handling the string in Go (go-lang)

README.md haven't contain all the examples. Please refer to the the XXXtest.go files.

Build Status Go Report Card GoDoc Coverage Status Go Walker GitHub version

Table of Contents

Installation

go get github.com/torden/go-strutil, import it as "github.com/torden/go-strutil", use it as StringProc or StringValidator

Examples

See the Example Source for more details

Processing Methods

AddSlashes

quote string with slashes.

func (s *StringProc) AddSlashes(str string) string

Example:

strutil := strutils.NewStringProc()
example_str := "a\bcdefgz"
fmt.Println("%v", strutil.AddSlashes(example_str))

The above example will output:

a\\bcdefgz
StripSlashes

Un-quotes a quoted string.

func (s *StringProc) StripSlashes(str string) string

Example:

strutil := NewStringProc()
example_str := "a\\bcdefgz"
fmt.Println("%v", strutil.StripSlashes(example_str))

The above example will output:

a\bcdefgz
NL2BR

breakstr inserted before looks like space (CRLF , LFCR, SPACE, NL).

func (s *StringProc) Nl2Br(str string) string

Example:

strutil := strutils.NewStringProc()
example_str := "abc\ndefgh"
fmt.Println("%v", strutil.Nl2Br(example_str))

The above example will output:

abc<br />defgh
BR2NL

replaces HTML line breaks to a newline

func (s *StringProc) Br2Nl(str string) string

Example:

strutil := strutils.NewStringProc()
example_str1 := "abc<br>defgh"
fmt.Println("%v", strutil.Br2Nl(example_str1))

example_str2 := "abc<br />defgh"
fmt.Println("%v", strutil.Br2Nl(example_str2))

example_str3 := "abc<br/>defgh"
fmt.Println("%v", strutil.Br2Nl(example_str3))

The above example will output:

abc\ndefgh
abc\ndefgh
abc\ndefgh
WordWrapSimple , WordWrapAround

Wraps a string to a given number of characters using break characters (TAB, SPACE)

func (s *StringProc) WordWrapSimple(str string, wd int, breakstr string) string
func (s *StringProc) WordWrapAround(str string, wd int, breakstr string) string

Example:

strutil := strutils.NewStringProc()
example_str := "The quick brown fox jumped over the lazy dog."
fmt.Printf("%v\n", strutil.WordWrapSimple(example_str, 3, "*"))
fmt.Printf("%v\n", strutil.WordWrapSimple(example_str, 8, "*"))

fmt.Printf("%v\n", strutil.WordWrapAround(example_str, 3, "*"))
fmt.Printf("%v\n", strutil.WordWrapAround(example_str, 8, "*"))

The above example will output:

The*quick*brown*fox*jumped*over*the*lazy*dog.
The quick*brown fox*jumped over*the lazy*dog.

The*quick*brown*fox*jumped*over*the*lazy*dog.
The quick*brown fox*jumped*over the*lazy*dog.
NumberFmt

format a number with english notation grouped thousands

func (s *StringProc) NumberFmt(obj interface{}) (string, error)

Example:

strutil := strutils.NewStringProc()
dataset := map[interface{}]string{
    123456789101112: "123,456,789,101,112",
    123456.1234:     "123,456.1234",
    -123456.1234:    "-123,456.1234",
    1.1234561e+06:   "1.1234561e+06",
    1234.1234:       "1,234.1234",
    12345.1234:      "12,345.1234",
    -1.1234561e+06:  "-1.1234561e+06",
    -12345.16:       "-12,345.16",
    12345.16:        "12,345.16",
    1234:            "1,234",
    12.12123098123:  "12.12123098123",
    1.212e+24:       "1.212e+24",
    123456789:       "123,456,789",
}

for k, v := range dataset {
    retval, err := strutil.NumberFmt(k)
    if v != retval {
        fmt.Errorf("Return Value mismatch.\nExpected: %v\nActual: %v", retval, v)
    } else if err != nil {
        fmt.Errorf("Return Error : %v", err)
    } else {
        fmt.Printf("%v\n", retval)
    }
}

The above example will output:

123,456,789,101,112
123,456.1234
-123,456.1234
1.1234561e+06
1,234.1234
12,345.1234
-1.1234561e+06
-12,345.16
12,345.16
1,234
12.12123098123
1.212e+24
123,456,789
PaddingBoth , PaddingLeft, PaddingRight

pad a string to a certain length with another string

func (s *StringProc) PaddingBoth(str string, fill string, mx int) string
func (s *StringProc) PaddingLeft(str string, fill string, mx int) string
func (s *StringProc) PaddingRight(str string, fill string, mx int) string

Example:

strutil := strutils.NewStringProc()
example_str := "Life isn't always what one like."

fmt.Printf("%v\n", strutil.PaddingBoth(example_str, "*", 38))
fmt.Printf("%v\n", strutil.PaddingLeft(example_str, "*", 38))
fmt.Printf("%v\n", strutil.PaddingRight(example_str, "*", 38))

fmt.Printf("%v\n", strutil.PaddingBoth(example_str, "*-=", 37))
fmt.Printf("%v\n", strutil.PaddingLeft(example_str, "*-=", 37))
fmt.Printf("%v\n", strutil.PaddingRight(example_str, "*-=", 37))

The above example will output:

***Life isn't always what one like.***
******Life isn't always what one like.
Life isn't always what one like.******
*-Life isn't always what one like.*-=
*-=*-Life isn't always what one like.
Life isn't always what one like.*-=*-
LowerCaseFirstWords

Lowercase the first character of each word in a string

// TOKEN : \t \r \n \f \v \s
func (s *StringProc) LowerCaseFirstWords(str string) string

Example:

strutil := strutils.NewStringProc()
example_str := "LIFE ISN'T ALWAYS WHAT ONE LIKE."
fmt.Printf("%v\n", strutil.LowerCaseFirstWords(example_str))

The above example will output:

lIFE iSN'T aLWAYS wHAT oNE lIKE.
UpperCaseFirstWords

Uppercase the first character of each word in a string

// TOKEN : \t \r \n \f \v \s
func (s *StringProc) UpperCaseFirstWords(str string) string

Example:

strutil := strutils.NewStringProc()
example_str := "life isn't always what one like."
fmt.Printf("%v\n", strutil.UpperCaseFirstWords(example_str))

The above example will output:

Life Isn't Always What One Like.
SwapCaseFirstWords

Switch the first character case of each word in a string

// TOKEN : \t \r \n \f \v \s
func (s *StringProc) SwapCaseFirstWords(str string) string

Example:

strutil := strutils.NewStringProc()
example_str := "O SAY, CAN YOU SEE, BY THE DAWN’S EARLY LIGHT,"
fmt.Printf("%v\n", strutil.UpperCaseFirstWords(example_str))

The above example will output:

o sAY, cAN yOU sEE, bY tHE dAWN’S eARLY lIGHT,
HumanByteSize

Byte Size convert to Easy Readable Size String

func (s *StringProc) HumanByteSize(obj interface{}, decimals int, unit uint8) (string, error)

Example:

strutil := strutils.NewStringProc()
example_str := 3276537856
fmt.Printf("%v\n", strutil.HumanByteSize(k, 2, CamelCaseDouble)

The above example will output:

3.05Gb
HumanFileSize

File Size convert to Easy Readable Size String

func (s *StringProc) HumanFileSize(filepath string, decimals int, unit uint8) (string, error)

Example:

strutil := strutils.NewStringProc()
example_str := 3276537856
fmt.Printf("%v\n", strutil.HumanFileSize("/tmp/java.tomcat.core", 2, CamelCaseDouble)

The above example will output:

3.05Gb
AnyCompare

AnyCompare is compares two same basic type (without prt) dataset (slice,map,single data).

func (s *StringProc) AnyCompare(obj1 interface{}, obj2 interface{}) (bool, error)

Example:

strutil := strutils.NewStringProc()

testComplexMap1 := map[string]map[string]map[string]int{
    "F": map[string]map[string]int{
        "name": map[string]int{
            "first": 1,
            "last":  2,
        },
    },
    "A": map[string]map[string]int{
        "name": map[string]int{
            "first": 11,
            "last":  21,
        },
    },
}

testComplexMap2 := map[string]map[string]map[string]int{
    "F": map[string]map[string]int{
        "name": map[string]int{
            "first": 11,
            "last":  12222,
        },
    },
    "A": map[string]map[string]int{
        "name": map[string]int{
            "first": 11,
            "last":  21,
        },
    },
}

retval, err = strproc.AnyCompare(testComplexMap1, testComplexMap2)

fmt.Println("Return : ", retval)
fmt.Println("Error : ", err)


The above example will output:

Return :  false
Error :  different value : (obj1[A][name][first][last][F][name][first] := 1) != (obj2[A][name][first][last][F][name][first] := 11)
StripTags

StipTags is remove all tag in string (Pure String or URL Encoded or Html Entity Encoded or Mixed String)

func (s *StringProc) StripTags(str string) (string, error)

Example:

strproc := strproc.NewStringProc()
example_str := `
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>                            Just! a String Processing Library for Go-lang</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#157878">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="/go-strutil/assets/css/style.css?v=dae229423409070462d2ce364eba3b5721930df0">
</head>
<body>
<section class="page-header">
<h1 class="project-name">Just! a String Processing Library for Go-lang</h1>
<h2 class="project-tagline">Just a few methods for helping processing and validation the string</h2>
<a href="https://github.com/torden/go-strutil" class="btn">View on GitHub</a>
</section>
<section class="main-content">
<h1 id="just-a-string-processing-library-for-go-lang">Just! a String Processing Library for Go-lang</h1>
<p>Just a few methods for helping processing the string</p>
<p>README.md haven’t contain all the examples. Please refer to the the XXXtest.go files.</p>
</body>
</html>
`
retval, err := strutil.StripTags(example_str)
if err != nil {
    fmt.Println("Error : ", err)
}
fmt.Println(retval)

The above example will output:

Just! a String Processing Library for Go-lang
Just! a String Processing Library for Go-lang
Just a few methods for helping processing and validation the string
View on GitHub
Just! a String Processing Library for Go-lang
Just a few methods for helping processing the string
README.md haven’t contain all the examples. Please refer to the the XXXtest.go files.
ConvertToStr

ConvertToStr is Convert basic data type to string

func (s *StringProc) ConvertToStr(obj interface{}) (string, error)

Example:

strproc := strproc.NewStringProc()
example_val := uint64(1234567)
retval, err := strutil.ConvertToStr(example_val)
if err != nil {
    fmt.Println("Error : ", err)
}
fmt.Println(retval)

The above example will output:

"1234567"
ReverseStr

ReverseStr is Reverse a String , According to value type between ascii (ReverseNormalStr) or rune (ReverseUnicode)

func (s *StringProc) ReverseStr(str string) string

Example:

strproc := strproc.NewStringProc()

dataset := []string{
  "0123456789",
  "가나다라마바사",
  "あいうえお",
  "天地玄黃宇宙洪荒",
}

strproc := strproc.NewStringProc()
for k, v := range dataset {
  fmt.Println(strproc.ReverseStr(k))
}

The above example will output:

9876543210
사바마라다나가
おえういあ
荒洪宙宇黃玄地天
ReverseNormalStr

ReverseNormalStr is Reverse a None-unicode String. Fast then ReverseUnicode or ReverseStr

func (s *StringProc) ReverseNormalStr(str string) string

Example:

strproc := strproc.NewStringProc()

dataset := []string{
  "0123456789",
  "abcdefg",
}

strproc := strproc.NewStringProc()
for k, v := range dataset {
  fmt.Println(strproc.ReverseNormalStr(k))
}

The above example will output:

9876543210
gfedcba
ReverseUnicode

ReverseNormalStr is Reverse a None-unicode String

func (s *StringProc) ReverseUnicode(str string) string

Example:

strproc := strproc.NewStringProc()

dataset := []string{
  "0123456789",
  "가나다라마바사",
  "あいうえお",
  "天地玄黃宇宙洪荒",
}

strproc := strproc.NewStringProc()
for k, v := range dataset {
  fmt.Println(strproc.ReverseUnicode(k))
}

The above example will output:

9876543210
사바마라다나가
おえういあ
荒洪宙宇黃玄地天
FileMD5Hash

FileMD5Hash is MD5 checksum of the file

func (s *StringProc) FileMD5Hash(filepath string) (string, error)

Example:

strproc := strutils.NewStringProc()

retval, err := strproc.FileMD5Hash("./LICENSE")
if err != nil {
    fmt.Println("Error : %v", err)
}

fmt.Println(retval)

The above example will output:

f3f8954bac465686f0bfc2a757c5200b
MD5Hash

MD5Hash is MD5 checksum of the string

func (s *StringProc) MD5Hash(str string) (string, error)

Example:

dataset := []string{
    "0123456789",
    "abcdefg",
    "abcdefgqwdoisef;oijawe;fijq2039jdfs.dnc;oa283hr08uj3o;ijwaef;owhjefo;uhwefwef",
}

strproc := strutils.NewStringProc()

//check : common
for _, v := range dataset {
    retval, err := strproc.MD5Hash(v)
    if err != nil {
        fmt.Println("Error : %v", err)
    } else {
      fmt.Println(retval)
    }
}

The above example will output:

781e5e245d69b566979b86e28d23f2c7
7ac66c0f148de9519b8bd264312c4d64
15f764f21d09b11102eb015fc8824d00

Validation Methods

IsValidEmail

IsValidEmail is Validates whether the value is a valid e-mail address.

func (s *StringValidator) IsValidEmail(str string) bool

Example:

strvalidator := strutils.NewStringValidator()
example_str := "a@golang.org"
fmt.Printf("%v\n", strvalidator.IsValidEmail(example_str))

The above example will output:

true
IsValidDomain

IsValidDomain is Validates whether the value is a valid domain address

func (s *StringValidator) IsValidDomain(str string) bool

Example:

strvalidator := strutils.NewStringValidator()
example_str := "golang.org"
fmt.Printf("%v\n", strvalidator.IsValidDomain(example_str))

The above example will output:

true
IsValidURL

IsValidURL is Validates whether the value is a valid url

func (s *StringValidator) IsValidURL(str string) bool

Example:

strvalidator := strutils.NewStringValidator()
example_str := "https://www.google.co.kr/url?sa=t&rct=j&q=&esrc=s&source=web"
fmt.Printf("%v\n", strvalidator.IsValidURL(example_str))

The above example will output:

true
IsValidMACAddr

IsValidMACAddr is Validates whether the value is a valid h/w mac address

func (s *StringValidator) IsValidMACAddr(str string) bool

Example:

strvalidator := strutils.NewStringValidator()
example_str := "02-f3-71-eb-9e-4b"
fmt.Printf("%v\n", strvalidator.IsValidMACAddr(example_str))

The above example will output:

true
IsValidIPAddr

IsValidIPAddr is Validates whether the value to be exactly a given validation types (IPv4, IPv6, IPv4MappedIPv6, IPv4CIDR, IPv6CIDR, IPv4MappedIPv6CIDR OR IPAny)

func (s *StringValidator) IsValidIPAddr(str string, cktypes ...int) (bool, error)

Example:

strvalidator := strutils.NewStringValidator()
example_str := "2001:470:1f09:495::3:217.126.185.21"
fmt.Printf("%v\n", strvalidator.IsValidIPAddr(example_str,strutils.IPv4MappedIPv6,strutils.IPv4))

The above example will output:

true
IsValidFilePath

IsValidFilePath is Validates whether the value is a valid FilePath without relative path

func (s *StringValidator) IsValidFilePath(str string) bool

Example:

strvalidator := strutils.NewStringValidator()
example_str := "a-1-s-d-v-we-wd_+qwd-qwd-qwd.txt
fmt.Printf("%v\n", strvalidator.IsValidFilePath(example_str))

The above example will output:

true
IsValidFilePathWithRelativePath

IsValidFilePathWithRelativePath is Validates whether the value is a valid FilePath (allow with relative path)

func (s *StringValidator) IsValidFilePathWithRelativePath(str string) bool

Example:

strvalidator := strutils.NewStringValidator()
example_str := "/asdasd/asdasdasd/qwdqwd_qwdqwd/12-12/a-1-e-r-t-_1_21234_d_1234_qwed_1423_.txt"
fmt.Printf("%v\n", strvalidator.IsValidFilePathWithRelativePath(example_str))

The above example will output:

true
IsPureTextStrict

IsPureTextStrict is Validates whether the value is a pure text, Validation use native

func (s *StringValidator) IsPureTextStrict(str string) (bool, error)

Example:

strvalidator := strutils.NewStringValidator()
example_str := `abcd/>qwdqwdoijhwer/>qwdojiqwdqwd</a>qwdoijqwdoiqjd`
fmt.Printf("%v\n", strvalidator.IsPureTextStrict(example_str))

The above example will output:

false
IsPureTextNormal

IsPureTextNormal is Validates whether the value is a pure text, Validation use Regular Expressions

func (s *StringValidator) IsPureTextNormal(str string) (bool, error)

Example:

strvalidator := strutils.NewStringValidator()
example_str := `Foo<script type="text/javascript">alert(1337)</script>Bar`
fmt.Printf("%v\n", strvalidator.IsPureTextNormal(example_str))

The above example will output:

false

Assertion Methods

AssertLog

AssertLog formats its arguments using default formatting, analogous to t.Log

AssertLog(t *testing.T, err error, msgfmt string, args ...interface{})
AssertEquals

AssertEquals asserts that two objects are equal.

AssertEquals(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})
AssertNotEquals

AssertNotEquals asserts that two objects are not equal.

AssertNotEquals(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})
AssertFalse

AssertFalse asserts that the specified value is false.

AssertFalse(t *testing.T, v1 bool, msgfmt string, args ...interface{})
AssertTrue

AssertTrue asserts that the specified value is true.

AssertTrue(t *testing.T, v1 bool, msgfmt string, args ...interface{})
AssertNil

AssertNil asserts that the specified value is nil.

AssertNil(t *testing.T, v1 interface{}, msgfmt string, args ...interface{})
AssertNotNil

AssertNotNil asserts that the specified value isn't nil.

AssertNotNil(t *testing.T, v1 interface{}, msgfmt string, args ...interface{})
AssertLessThan

AssertLessThan asserts that the specified value are v1 less than v2

AssertLessThan(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})
AssertLessThanEqualTo

AssertLessThanEqualTo asserts that the specified value are v1 less than v2 or equal to

AssertLessThanEqualTo(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})
AssertGreaterThan

AssertGreaterThan nsserts that the specified value are v1 greater than v2

AssertGreaterThan(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})
AssertGreaterThanEqualTo

AssertGreaterThanEqualTo asserts that the specified value are v1 greater than v2 or equal to

AssertGreaterThanEqualTo(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})
AssertLengthOf

AssertLengthOf asserts that object has a length property with the expected value.

AssertLengthOf(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})

Please feel free. I hope it is helpful for you

Documentation

Overview

Package strutils made by torden <https://github.com/torden/go-strutil> license that can be found in the LICENSE file.

Example (Strutils_AddSlashes)
strproc := strutils.NewStringProc()
example_str := `a\bcdefgz`
fmt.Println(strproc.AddSlashes(example_str))
Output:

a\\bcdefgz
Example (Strutils_AnyCompare)
strproc := strutils.NewStringProc()

testComplexMap1 := map[string]map[string]map[string]int{
	"F": {
		"name": {
			"first": 1,
			"last":  2,
		},
	},
	"A": {
		"name": {
			"first": 11,
			"last":  21,
		},
	},
}

testComplexMap2 := map[string]map[string]map[string]int{
	"F": {
		"name": {
			"first": 11,
			"last":  12222,
		},
	},
	"A": {
		"name": {
			"first": 11,
			"last":  21,
		},
	},
}

var retval bool
var err error

retval, err = strproc.AnyCompare(testComplexMap1, testComplexMap2)
fmt.Println("Return : ", retval)
fmt.Println("Error : ", err)
Output:

Example (Strutils_ConvertToStr)
strproc := strutils.NewStringProc()
example_val := uint64(1234567)
retval, err := strproc.ConvertToStr(example_val)
if err != nil {
	fmt.Println("Error : ", err)
}
fmt.Println(retval)

// Output : "1234567"
Output:

Example (Strutils_FileMD5Hash)
strproc := strutils.NewStringProc()

retval, err := strproc.FileMD5Hash("./LICENSE")
if err != nil {
	fmt.Printf("Error : %v", err)
}

fmt.Println(retval)
Output:

64e17a4e1c96bbfce57ab19cd0153e6a
Example (Strutils_HumanByteSize)
strproc := strutils.NewStringProc()
example_str := 3276537856
retval, err := strproc.HumanByteSize(example_str, 2, strutils.CamelCaseLong)
if err != nil {
	fmt.Println("Error : ", err)
} else {
	fmt.Println(retval)
}
Output:

3.05GigaByte
Example (Strutils_HumanFileSize)
const tmpFilePath = "./filesizecheck.touch"
var retval string
var err error

//generating a touch file
tmpdata := []byte("123456789")

err = ioutil.WriteFile(tmpFilePath, tmpdata, 0750)
if err != nil {
	fmt.Println("Error : ", err)
}

strproc := strutils.NewStringProc()
retval, err = strproc.HumanFileSize(tmpFilePath, 2, strutils.CamelCaseLong)
if err != nil {
	fmt.Println("Error : ", err)
} else {
	fmt.Println(retval)
}

retval, err = strproc.HumanFileSize(tmpFilePath, 2, strutils.CamelCaseDouble)
if err != nil {
	fmt.Println("Error : ", err)
} else {
	fmt.Println(retval)
}

err = os.Remove(tmpFilePath)
if err != nil {
	fmt.Println("Error : ", err)
}
Output:

9.00Byte
9.00B
Example (Strutils_IsPureTextNormal)
strvalidator := strutils.NewStringValidator()
example_str := `Foo<script type="text/javascript">alert(1337)</script>Bar`
retval, err := strvalidator.IsPureTextNormal(example_str)

if err != nil {
	fmt.Println("Error : ", err)
} else {
	fmt.Println(retval)
}
Output:

Error :  Detect HTML Element
Example (Strutils_IsPureTextStrict)
strvalidator := strutils.NewStringValidator()
example_str := `abcd/>qwdqwdoijhwer/>qwdojiqwdqwd</a>qwdoijqwdoiqjd`
retval, err := strvalidator.IsPureTextStrict(example_str)
if err != nil {
	fmt.Println("Error : ", err)
} else {
	fmt.Println(retval)
}
Output:

Error :  Detect Tag (<[!|?]~>)
Example (Strutils_IsValidDomain)
strvalidator := strutils.NewStringValidator()
example_str := "golang.org"
fmt.Printf("%v\n", strvalidator.IsValidDomain(example_str))
Output:

true
Example (Strutils_IsValidEmail)
strvalidator := strutils.NewStringValidator()
example_str := "a@golang.org"
fmt.Printf("%v\n", strvalidator.IsValidEmail(example_str))
Output:

true
Example (Strutils_IsValidFilePath)
strvalidator := strutils.NewStringValidator()
example_str := "a-1-s-d-v-we-wd_+qwd-qwd-qwd.txt"
fmt.Printf("%v\n", strvalidator.IsValidFilePath(example_str))
Output:

false
Example (Strutils_IsValidFilePathWithRelativePath)
strvalidator := strutils.NewStringValidator()
example_str := "/asdasd/asdasdasd/qwdqwd_qwdqwd/12-12/a-1-e-r-t-_1_21234_d_1234_qwed_1423_.txt"
fmt.Printf("%v\n", strvalidator.IsValidFilePathWithRelativePath(example_str))
Output:

true
Example (Strutils_IsValidIPAddr)
strvalidator := strutils.NewStringValidator()
example_str := "2001:470:1f09:495::3:217.126.185.21"
retval, err := strvalidator.IsValidIPAddr(example_str, strutils.IPv4MappedIPv6, strutils.IPv4)
if err != nil {
	fmt.Println("Error : ", err)
} else {
	fmt.Println(retval)
}
Output:

true
Example (Strutils_IsValidMACAddr)
strvalidator := strutils.NewStringValidator()
example_str := "02-f3-71-eb-9e-4b"
fmt.Printf("%v\n", strvalidator.IsValidMACAddr(example_str))
Output:

true
Example (Strutils_IsValidURL)
strvalidator := strutils.NewStringValidator()
example_str := "https://www.google.co.kr/url?sa=t&rct=j&q=&esrc=s&source=web"
fmt.Printf("%v\n", strvalidator.IsValidURL(example_str))
Output:

true
Example (Strutils_LowerCaseFirstWords)
strproc := strutils.NewStringProc()
example_str := "LIFE ISN'T ALWAYS WHAT ONE LIKE."
fmt.Printf("%v\n", strproc.LowerCaseFirstWords(example_str))
Output:

lIFE iSN'T aLWAYS wHAT oNE lIKE.
Example (Strutils_MD5Hash)
dataset := []string{
	"0123456789",
	"abcdefg",
	"abcdefgqwdoisef;oijawe;fijq2039jdfs.dnc;oa283hr08uj3o;ijwaef;owhjefo;uhwefwef",
}

strproc := strutils.NewStringProc()

//check : common
for _, v := range dataset {
	retval, err := strproc.MD5Hash(v)
	if err != nil {
		fmt.Printf("Error : %v", err)
	} else {
		fmt.Println(retval)
	}
}

// Output : 781e5e245d69b566979b86e28d23f2c7
// 7ac66c0f148de9519b8bd264312c4d64
// 15f764f21d09b11102eb015fc8824d00
Output:

Example (Strutils_Nl2Br)
strproc := strutils.NewStringProc()
example_str := "abc\ndefgh"
fmt.Println(strproc.Nl2Br(example_str))
Output:

abc<br />defgh
Example (Strutils_NumberFmt)
strproc := strutils.NewStringProc()

var retval string

retval, _ = strproc.NumberFmt(123456789101112)
fmt.Println(retval)
Output:

Example (Strutils_PaddingBoth)
strproc := strutils.NewStringProc()
example_str := "Life isn't always what one like."

fmt.Printf("%v\n", strproc.PaddingBoth(example_str, "*", 38))
fmt.Printf("%v\n", strproc.PaddingBoth(example_str, "*-=", 37))
Output:

***Life isn't always what one like.***
*-Life isn't always what one like.*-=
Example (Strutils_PaddingLeft)
strproc := strutils.NewStringProc()
example_str := "Life isn't always what one like."

fmt.Printf("%v\n", strproc.PaddingLeft(example_str, "*", 38))
fmt.Printf("%v\n", strproc.PaddingLeft(example_str, "*-=", 37))
Output:

******Life isn't always what one like.
*-=*-Life isn't always what one like.
Example (Strutils_PaddingRight)
strproc := strutils.NewStringProc()
example_str := "Life isn't always what one like."

fmt.Printf("%v\n", strproc.PaddingRight(example_str, "*", 38))
fmt.Printf("%v\n", strproc.PaddingRight(example_str, "*-=", 37))
Output:

Life isn't always what one like.******
Life isn't always what one like.*-=*-
Example (Strutils_ReverseNormalStr)
dataset := []string{
	"0123456789",
	"abcdefg",
}

strproc := strutils.NewStringProc()
for _, v := range dataset {
	fmt.Println(strproc.ReverseNormalStr(v))
}

// Output : 9876543210
//gfedcba
Output:

Example (Strutils_ReverseReverseUnicode)
dataset := []string{
	"0123456789",
	"가나다라마바사",
	"あいうえお",
	"天地玄黃宇宙洪荒",
}

strproc := strutils.NewStringProc()
for _, v := range dataset {
	fmt.Println(strproc.ReverseUnicode(v))
}

// Output : 9876543210
//사바마라다나가
//おえういあ
//荒洪宙宇黃玄地天
Output:

Example (Strutils_ReverseStr)
dataset := []string{
	"0123456789",
	"가나다라마바사",
	"あいうえお",
	"天地玄黃宇宙洪荒",
}

strproc := strutils.NewStringProc()
for _, v := range dataset {
	fmt.Println(strproc.ReverseStr(v))
}

// Output : 9876543210
//사바마라다나가
//おえういあ
//荒洪宙宇黃玄地天
Output:

Example (Strutils_StripSlashes)
strproc := strutils.NewStringProc()
example_str := "a\\bcdefgz"
fmt.Println(strproc.StripSlashes(example_str))
Output:

abcdefgz
Example (Strutils_StripTags)
strproc := strutils.NewStringProc()
example_str := `
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>                            Just! a String Processing Library for Go-lang</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#157878">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="/go-strutil/assets/css/style.css?v=dae229423409070462d2ce364eba3b5721930df0">
</head>
<body>
<section class="page-header">
<h1 class="project-name">Just! a String Processing Library for Go-lang</h1>
<h2 class="project-tagline">Just a few methods for helping processing and validation the string</h2>
<a href="https://github.com/torden/go-strutil" class="btn">View on GitHub</a>
</section>
<section class="main-content">
<h1 id="just-a-string-processing-library-for-go-lang">Just! a String Processing Library for Go-lang</h1>
<p>Just a few methods for helping processing the string</p>
<p>README.md haven’t contain all the examples. Please refer to the the XXXtest.go files.</p>
</body>
</html>
`
retval, err := strproc.StripTags(example_str)
if err != nil {
	fmt.Println("Error : ", err)
}
fmt.Println(retval)

// 	Output :Just! a String Processing Library for Go-lang
//Just! a String Processing Library for Go-lang
//Just a few methods for helping processing and validation the string
//View on GitHub
//Just! a String Processing Library for Go-lang
//Just a few methods for helping processing the string
//README.md haven’t contain all the examples. Please refer to the the XXXtest.go files.
Output:

Example (Strutils_SwapCaseFirstWords)
strproc := strutils.NewStringProc()
example_str := "O SAY, CAN YOU SEE, BY THE DAWN’S EARLY LIGHT,"
fmt.Printf("%v\n", strproc.UpperCaseFirstWords(example_str))
Output:

O SAY, CAN YOU SEE, BY THE DAWN’S EARLY LIGHT,
Example (Strutils_UpperCaseFirstWords)
strproc := strutils.NewStringProc()
example_str := "life isn't always what one like."
fmt.Printf("%v\n", strproc.UpperCaseFirstWords(example_str))
Output:

Life Isn't Always What One Like.
Example (Strutils_WordWrapAround)
strproc := strutils.NewStringProc()
example_str := "The quick brown fox jumped over the lazy dog."

var retval string
var err error
retval, err = strproc.WordWrapAround(example_str, 3, "*")
if err != nil {
	fmt.Println("Error : ", err)
} else {
	fmt.Printf("%v\n", retval)
}

retval, _ = strproc.WordWrapAround(example_str, 8, "*")
if err != nil {
	fmt.Println("Error : ", err)
} else {
	fmt.Printf("%v\n", retval)
}
Output:

The*quick*brown*fox*jumped*over*the*lazy*dog.
The quick*brown fox*jumped*over the*lazy*dog.
Example (Strutils_WordWrapSimple)
strproc := strutils.NewStringProc()
example_str := "The quick brown fox jumped over the lazy dog."

var retval string
retval, _ = strproc.WordWrapSimple(example_str, 3, "*")
fmt.Printf("%v\n", retval)

retval, _ = strproc.WordWrapSimple(example_str, 8, "*")
fmt.Printf("%v\n", retval)
Output:

The*quick*brown*fox*jumped*over*the*lazy*dog.
The quick*brown fox*jumped over*the lazy*dog.

Index

Examples

Constants

View Source
const (
	PadLeft  = 0 //left padding
	PadRight = 1 //right padding
	PadBoth  = 2 //both padding
)

padding contol const

View Source
const (
	LowerCaseSingle // Single Unit character converted to Lower-case
	LowerCaseDouble // Double Unit characters converted to Lower-case

	UpperCaseSingle // Single Unit character converted to Uppper-case
	UpperCaseDouble // Double Unit characters converted to Upper-case

	CamelCaseDouble // Double Unit characters converted to Camel-case
	CamelCaseLong   // Full Unit characters converted to Camel-case
)

Unit type control

View Source
const (
	IPAny              = 1
	IPv4               = 32
	IPv6               = 39
	IPv4MappedIPv6     = 45
	IPv4CIDR           = IPv4 + 3
	IPv6CIDR           = IPv6 + 3
	IPv4MappedIPv6CIDR = IPv4MappedIPv6 + 3
)

This consts for cktypes of IsValidIPAddr IPAny // Any IP Address Type IPv4 // IPv4 (32 chars) IPv6 // IPv6(39 chars) IPv4MappedIPv6 // IP4-mapped IPv6 (45 chars) , Ex) ::FFFF:129.144.52.38 IPv4CIDR // IPv4 + CIDR IPv6CIDR // IPv6 + CIDR IPv4MappedIPv6CIDR //IPv4-mapped IPv6 + CIRD

View Source
const UNITTESTMODE = true

UNITTESTMODE runs on go [run|build] -flags unittest command

Variables

This section is empty.

Functions

This section is empty.

Types

type Assert

type Assert struct {
	// contains filtered or unexported fields
}

Assert is Methods for helping testing the strutils pkg.

func NewAssert

func NewAssert() *Assert

NewAssert Creates and returns a String processing methods's pointer.

func (*Assert) AssertEquals

func (a *Assert) AssertEquals(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})

AssertEquals asserts that two objects are equal.

func (*Assert) AssertFalse

func (a *Assert) AssertFalse(t *testing.T, v1 bool, msgfmt string, args ...interface{})

AssertFalse asserts that the specified value is false.

func (*Assert) AssertGreaterThan

func (a *Assert) AssertGreaterThan(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})

AssertGreaterThan nsserts that the specified value are v1 greater than v2

func (*Assert) AssertGreaterThanEqualTo

func (a *Assert) AssertGreaterThanEqualTo(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})

AssertGreaterThanEqualTo asserts that the specified value are v1 greater than v2 or equal to

func (*Assert) AssertLengthOf added in v0.0.3

func (a *Assert) AssertLengthOf(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})

AssertLengthOf asserts that object has a length property with the expected value.

func (*Assert) AssertLessThan

func (a *Assert) AssertLessThan(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})

AssertLessThan asserts that the specified value are v1 less than v2

func (*Assert) AssertLessThanEqualTo

func (a *Assert) AssertLessThanEqualTo(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})

AssertLessThanEqualTo asserts that the specified value are v1 less than v2 or equal to

func (*Assert) AssertLog

func (a *Assert) AssertLog(t *testing.T, err error, msgfmt string, args ...interface{})

AssertLog formats its arguments using default formatting, analogous to t.Log

func (*Assert) AssertNil

func (a *Assert) AssertNil(t *testing.T, v1 interface{}, msgfmt string, args ...interface{})

AssertNil asserts that the specified value is nil.

func (*Assert) AssertNotEquals added in v0.0.2

func (a *Assert) AssertNotEquals(t *testing.T, v1 interface{}, v2 interface{}, msgfmt string, args ...interface{})

AssertNotEquals asserts that two objects are not equal.

func (*Assert) AssertNotNil

func (a *Assert) AssertNotNil(t *testing.T, v1 interface{}, msgfmt string, args ...interface{})

AssertNotNil asserts that the specified value isn't nil.

func (*Assert) AssertTrue

func (a *Assert) AssertTrue(t *testing.T, v1 bool, msgfmt string, args ...interface{})

AssertTrue asserts that the specified value is true.

func (*Assert) TurnOffUnitTestMode added in v0.1.2

func (a *Assert) TurnOffUnitTestMode()

RevertUnitTestMode is revert unitTestMode

func (*Assert) TurnOnUnitTestMode added in v0.1.2

func (a *Assert) TurnOnUnitTestMode()

TurnOffUnitTestMode is turn off unitTestMode

type StringProc

type StringProc struct {
	sync.RWMutex
}

StringProc is String processing methods, All operations on this object

func NewStringProc

func NewStringProc() *StringProc

NewStringProc Creates and returns a String processing methods's pointer.

func (*StringProc) AddSlashes

func (s *StringProc) AddSlashes(str string) string

AddSlashes is quote string with slashes

func (*StringProc) AnyCompare

func (s *StringProc) AnyCompare(obj1 interface{}, obj2 interface{}) (bool, error)

AnyCompare is compares two same basic type (without prt) dataset (slice,map,single data). TODO : support interface, struct ... NOTE : Not safe , Not Test Complete. Require more test data based on the complex dataset.

func (*StringProc) Br2Nl added in v0.1.2

func (s *StringProc) Br2Nl(str string) string

Br2Nl is replaces HTML line breaks to a newline

func (*StringProc) ConvertToArByte added in v0.0.2

func (s *StringProc) ConvertToArByte(obj interface{}) ([]byte, error)

ConvertToArByte returns Convert basic data type to []byte

func (*StringProc) ConvertToStr

func (s *StringProc) ConvertToStr(obj interface{}) (string, error)

ConvertToStr is Convert basic data type to string

func (*StringProc) FileMD5Hash

func (s *StringProc) FileMD5Hash(filepath string) (string, error)

FileMD5Hash is MD5 checksum of the file

func (*StringProc) HumanByteSize

func (s *StringProc) HumanByteSize(obj interface{}, decimals int, unit uint8) (string, error)

HumanByteSize is Byte Size convert to Easy Readable Size String

func (*StringProc) HumanFileSize

func (s *StringProc) HumanFileSize(filepath string, decimals int, unit uint8) (string, error)

HumanFileSize is File Size convert to Easy Readable Size String

func (*StringProc) LowerCaseFirstWords

func (s *StringProc) LowerCaseFirstWords(str string) string

LowerCaseFirstWords is Lowercase the first character of each word in a string INFO : (Support Token Are \t(9)\r(13)\n(10)\f(12)\v(11)\s(32))

func (*StringProc) MD5Hash

func (s *StringProc) MD5Hash(str string) (string, error)

MD5Hash is MD5 checksum of the string

func (*StringProc) Nl2Br

func (s *StringProc) Nl2Br(str string) string

Nl2Br is breakstr inserted before looks like space (CRLF , LFCR, SPACE, NL)

func (*StringProc) NumberFmt

func (s *StringProc) NumberFmt(obj interface{}) (string, error)

NumberFmt is format a number with english notation grouped thousands TODO : support other country notation

func (*StringProc) Padding

func (s *StringProc) Padding(str string, fill string, m int, mx int) string

Padding is Pad a string to a certain length with another string BenchmarkPadding-8 10000000 271 ns/op BenchmarkPaddingUseStringRepeat-8 3000000 418 ns/op

func (*StringProc) PaddingBoth

func (s *StringProc) PaddingBoth(str string, fill string, mx int) string

PaddingBoth is Padding method alias with PadBoth Option

func (*StringProc) PaddingLeft

func (s *StringProc) PaddingLeft(str string, fill string, mx int) string

PaddingLeft is Padding method alias with PadRight Option

func (*StringProc) PaddingRight

func (s *StringProc) PaddingRight(str string, fill string, mx int) string

PaddingRight is Padding method alias with PadRight Option

func (*StringProc) ReverseNormalStr

func (s *StringProc) ReverseNormalStr(str string) string

ReverseNormalStr is Reverse a None-unicode String

func (*StringProc) ReverseStr

func (s *StringProc) ReverseStr(str string) string

ReverseStr is Reverse a String , According to value type between ascii or rune TODO : improve performance (use goroutin)

func (*StringProc) ReverseUnicode

func (s *StringProc) ReverseUnicode(str string) string

ReverseUnicode is Reverse a unicode String

func (*StringProc) StripSlashes

func (s *StringProc) StripSlashes(str string) string

StripSlashes is Un-quotes a quoted string

func (*StringProc) StripTags

func (s *StringProc) StripTags(str string) (string, error)

StripTags is remove all tag in string

func (*StringProc) SwapCaseFirstWords

func (s *StringProc) SwapCaseFirstWords(str string) string

SwapCaseFirstWords is Switch the first character case of each word in a string

func (*StringProc) UpperCaseFirstWords

func (s *StringProc) UpperCaseFirstWords(str string) string

UpperCaseFirstWords is Uppercase the first character of each word in a string INFO : (Support Token Are \t(9)\r(13)\n(10)\f(12)\v(11)\s(32))

func (*StringProc) WordWrapAround

func (s *StringProc) WordWrapAround(str string, wd int, breakstr string) (string, error)

WordWrapAround is Wraps a string to a given number of characters using break characters (TAB, SPACE)

func (*StringProc) WordWrapSimple

func (s *StringProc) WordWrapSimple(str string, wd int, breakstr string) (string, error)

WordWrapSimple is Wraps a string to a given number of characters using break characters (TAB, SPACE)

type StringValidator

type StringValidator struct{}

StringValidator is String processing methods, All operations on this object

func NewStringValidator

func NewStringValidator() *StringValidator

NewStringValidator is Creates and returns a String processing methods's pointer.

func (*StringValidator) IsPureTextNormal

func (s *StringValidator) IsPureTextNormal(str string) (bool, error)

IsPureTextNormal is Validates whether the value is a pure text, Validation use Regular Expressions

func (*StringValidator) IsPureTextStrict

func (s *StringValidator) IsPureTextStrict(str string) (bool, error)

IsPureTextStrict is Validates whether the value is a pure text, Validation use native

func (*StringValidator) IsValidDomain

func (s *StringValidator) IsValidDomain(str string) bool

IsValidDomain is Validates whether the value is a valid domain address

func (*StringValidator) IsValidEmail

func (s *StringValidator) IsValidEmail(str string) bool

IsValidEmail is Validates whether the value is a valid e-mail address.

func (*StringValidator) IsValidFilePath

func (s *StringValidator) IsValidFilePath(str string) bool

IsValidFilePath is Validates whether the value is a valid FilePath without relative path

func (*StringValidator) IsValidFilePathWithRelativePath

func (s *StringValidator) IsValidFilePathWithRelativePath(str string) bool

IsValidFilePathWithRelativePath is Validates whether the value is a valid FilePath (allow with relative path)

func (*StringValidator) IsValidIPAddr

func (s *StringValidator) IsValidIPAddr(str string, cktypes ...int) (bool, error)

IsValidIPAddr is Validates whether the value to be exactly a given validation type (IPv4, IPv6, IPv4MappedIPv6, IPv4CIDR, IPv6CIDR, IPv4MappedIPv6CIDR OR IPAny)

func (*StringValidator) IsValidMACAddr

func (s *StringValidator) IsValidMACAddr(str string) bool

IsValidMACAddr is Validates whether the value is a valid h/w mac address

func (*StringValidator) IsValidURL

func (s *StringValidator) IsValidURL(str string) bool

IsValidURL is Validates whether the value is a valid url

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL