├── LICENSE ├── README.md ├── algorithm ├── LRUCache.go ├── bitmap.go ├── skiplist.go └── stack.go ├── clcolor └── clcolor.go └── utils ├── dtutil.go └── regutil.go /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | xclpkg 2 | ====== 3 | 4 | Golang Package 5 | -------------------------------------------------------------------------------- /algorithm/LRUCache.go: -------------------------------------------------------------------------------- 1 | package algorithm 2 | 3 | 4 | //LRU Cache 5 | //author:Xiong Chuan Liang 6 | //date:2015-2-3 7 | //"github.com/xcltapestry/xclpkg/algorithm" 8 | 9 | import ( 10 | "container/list" 11 | "errors" 12 | ) 13 | 14 | 15 | type CacheNode struct { 16 | Key,Value interface{} 17 | } 18 | 19 | func (cnode *CacheNode)NewCacheNode(k,v interface{})*CacheNode{ 20 | return &CacheNode{k,v} 21 | } 22 | 23 | type LRUCache struct { 24 | Capacity int 25 | dlist *list.List 26 | cacheMap map[interface{}]*list.Element 27 | } 28 | 29 | func NewLRUCache(cap int)(*LRUCache){ 30 | return &LRUCache{ 31 | Capacity:cap, 32 | dlist: list.New(), 33 | cacheMap: make(map[interface{}]*list.Element)} 34 | } 35 | 36 | func (lru *LRUCache)Size()(int){ 37 | return lru.dlist.Len() 38 | } 39 | 40 | func (lru *LRUCache)Set(k,v interface{})(error){ 41 | 42 | if lru.dlist == nil { 43 | return errors.New("LRUCache结构体未初始化.") 44 | } 45 | 46 | if pElement,ok := lru.cacheMap[k]; ok { 47 | lru.dlist.MoveToFront(pElement) 48 | pElement.Value.(*CacheNode).Value = v 49 | return nil 50 | } 51 | 52 | newElement := lru.dlist.PushFront( &CacheNode{k,v} ) 53 | lru.cacheMap[k] = newElement 54 | 55 | if lru.dlist.Len() > lru.Capacity { 56 | //移掉最后一个 57 | lastElement := lru.dlist.Back() 58 | if lastElement == nil { 59 | return nil 60 | } 61 | cacheNode := lastElement.Value.(*CacheNode) 62 | delete(lru.cacheMap,cacheNode.Key) 63 | lru.dlist.Remove(lastElement) 64 | } 65 | return nil 66 | } 67 | 68 | 69 | func (lru *LRUCache)Get(k interface{})(v interface{},ret bool,err error){ 70 | 71 | if lru.cacheMap == nil { 72 | return v,false,errors.New("LRUCache结构体未初始化.") 73 | } 74 | 75 | if pElement,ok := lru.cacheMap[k]; ok { 76 | lru.dlist.MoveToFront(pElement) 77 | return pElement.Value.(*CacheNode).Value,true,nil 78 | } 79 | return v,false,nil 80 | } 81 | 82 | 83 | func (lru *LRUCache)Remove(k interface{})(bool){ 84 | 85 | if lru.cacheMap == nil { 86 | return false 87 | } 88 | 89 | if pElement,ok := lru.cacheMap[k]; ok { 90 | cacheNode := pElement.Value.(*CacheNode) 91 | delete(lru.cacheMap,cacheNode.Key) 92 | lru.dlist.Remove(pElement) 93 | return true 94 | } 95 | return false 96 | } 97 | 98 | -------------------------------------------------------------------------------- /algorithm/bitmap.go: -------------------------------------------------------------------------------- 1 | package algorithm 2 | 3 | //Bitmap 4 | //author:Xiong Chuan Liang 5 | //date:2014-1-25 6 | 7 | import ( 8 | "fmt" 9 | ) 10 | 11 | const ( 12 | BitSize = 8 //一个字节8位 13 | ) 14 | 15 | type Bitmap struct { 16 | BitArray []byte 17 | ArraySize uint32 18 | } 19 | 20 | func NewBitmap(max uint32) *Bitmap { 21 | var r uint32 22 | switch { 23 | case max <= BitSize: 24 | r = 1 25 | default: 26 | r = max / BitSize 27 | if max%BitSize != 0 { 28 | r += 1 29 | } 30 | } 31 | 32 | fmt.Println("数组大小:", r) 33 | return &Bitmap{BitArray: make([]byte, r), ArraySize: r} 34 | } 35 | 36 | func (bitmap *Bitmap) Set(i uint32) { 37 | idx, pos := bitmap.calc(i) 38 | bitmap.BitArray[idx] |= 1 << pos 39 | fmt.Println("set() value=", i, " idx=", idx, " pos=", pos, ByteToBinaryString(bitmap.BitArray[idx])) 40 | } 41 | 42 | func (bitmap *Bitmap) Test(i uint32) byte { 43 | idx, pos := bitmap.calc(i) 44 | return bitmap.BitArray[idx] >> pos & 1 45 | } 46 | 47 | func (bitmap *Bitmap) Clear(i uint32) { 48 | idx, pos := bitmap.calc(i) 49 | bitmap.BitArray[idx] &^= 1 << pos 50 | } 51 | 52 | func (bitmap *Bitmap) calc(i uint32) (idx, pos uint32) { 53 | 54 | idx = i >> 3 //相当于i / 8,即字节位置 55 | if idx >= bitmap.ArraySize { 56 | panic("数组越界.") 57 | return 58 | } 59 | pos = i % BitSize //位位置 60 | return 61 | } 62 | 63 | //ByteToBinaryString函数来源: 64 | // Go语言版byte变量的二进制字符串表示 65 | // http://www.sharejs.com/codes/go/4357 66 | func ByteToBinaryString(data byte) (str string) { 67 | var a byte 68 | for i := 0; i < 8; i++ { 69 | a = data 70 | data <<= 1 71 | data >>= 1 72 | 73 | switch a { 74 | case data: 75 | str += "0" 76 | default: 77 | str += "1" 78 | } 79 | 80 | data <<= 1 81 | } 82 | return str 83 | } 84 | -------------------------------------------------------------------------------- /algorithm/skiplist.go: -------------------------------------------------------------------------------- 1 | package algorithm 2 | 3 | //SkipList 4 | //author:Xiong Chuan Liang 5 | //date:2014-1-28 6 | //"github.com/xcltapestry/xclpkg/algorithm" 7 | 8 | import ( 9 | //"fmt" 10 | "math/rand" 11 | ) 12 | 13 | 14 | const SKIPLIST_MAXLEVEL = 32 //8 15 | const SKIPLIST_P = 4 16 | 17 | 18 | type Node struct { 19 | Forward []Node 20 | Value interface{} 21 | } 22 | 23 | 24 | func NewNode(v interface{},level int) *Node { 25 | return &Node{Value: v, Forward: make([]Node, level)} 26 | } 27 | 28 | 29 | type SkipList struct { 30 | Header *Node 31 | Level int 32 | } 33 | 34 | func NewSkipList() *SkipList { 35 | return &SkipList{Level: 1, Header: NewNode(0,SKIPLIST_MAXLEVEL)} 36 | } 37 | 38 | func (skipList *SkipList) Insert(key int) { 39 | 40 | update := make(map[int]*Node) 41 | node := skipList.Header 42 | 43 | for i := skipList.Level - 1; i >= 0; i-- { 44 | for { 45 | if node.Forward[i].Value != nil && node.Forward[i].Value.(int) < key { 46 | node = &node.Forward[i] 47 | }else{ 48 | break; 49 | } 50 | } 51 | update[i] = node 52 | } 53 | 54 | level := skipList.Random_level() 55 | if level > skipList.Level { 56 | for i := skipList.Level; i < level; i++ { 57 | update[i] = skipList.Header 58 | } 59 | skipList.Level = level 60 | } 61 | 62 | newNode := NewNode(key,level) 63 | 64 | for i := 0; i < level; i++ { 65 | newNode.Forward[i] = update[i].Forward[i] 66 | update[i].Forward[i] = *newNode 67 | } 68 | 69 | } 70 | 71 | func (skipList *SkipList) Random_level() int { 72 | 73 | level := 1 74 | for (rand.Int31()&0xFFFF)%SKIPLIST_P == 0 { 75 | level += 1 76 | } 77 | if level < SKIPLIST_MAXLEVEL { 78 | return level 79 | } else { 80 | return SKIPLIST_MAXLEVEL 81 | } 82 | } 83 | 84 | func (skipList *SkipList) PrintSkipList() { 85 | 86 | //fmt.Println("\nSkipList-------------------------------------------") 87 | for i := SKIPLIST_MAXLEVEL - 1; i >= 0; i-- { 88 | 89 | //fmt.Println("level:", i) 90 | node := skipList.Header.Forward[i] 91 | for { 92 | if node.Value != nil { 93 | //fmt.Printf("%d ", node.Value.(int)) 94 | node = node.Forward[i] 95 | }else{ 96 | break; 97 | } 98 | } 99 | //fmt.Println("\n--------------------------------------------------------") 100 | } //end for 101 | 102 | //fmt.Println("Current MaxLevel:", skipList.Level) 103 | } 104 | 105 | 106 | func (skipList *SkipList) Search(key int) *Node { 107 | 108 | node := skipList.Header 109 | for i := skipList.Level - 1; i >= 0; i-- { 110 | 111 | //fmt.Println("\n Search() Level=", i) 112 | for { 113 | if node.Forward[i].Value == nil { 114 | break 115 | } 116 | 117 | //fmt.Printf(" %d ", node.Forward[i].Value) 118 | if node.Forward[i].Value.(int) == key { 119 | //fmt.Println("\nFound level=", i, " key=", key) 120 | return &node.Forward[i] 121 | } 122 | 123 | if node.Forward[i].Value.(int) < key { 124 | node = &node.Forward[i] 125 | continue 126 | }else{ // > key 127 | break 128 | } 129 | } //end for find 130 | 131 | } //end level 132 | return nil 133 | } 134 | 135 | 136 | func (skipList *SkipList)Remove(key int) { 137 | 138 | update := make(map[int]*Node) 139 | node := skipList.Header 140 | for i := skipList.Level - 1; i >= 0; i-- { 141 | 142 | for { 143 | 144 | if node.Forward[i].Value == nil { 145 | break 146 | } 147 | 148 | if node.Forward[i].Value.(int) == key { 149 | //fmt.Println("Remove() level=", i, " key=", key) 150 | update[i] = node 151 | break 152 | } 153 | 154 | if node.Forward[i].Value.(int) < key { 155 | node = &node.Forward[i] 156 | continue 157 | }else{ // > key 158 | break 159 | } 160 | 161 | } //end for find 162 | 163 | } //end level 164 | 165 | for i,v := range update { 166 | if v == skipList.Header { 167 | skipList.Level -- 168 | } 169 | v.Forward[i] = v.Forward[i].Forward[i] 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /algorithm/stack.go: -------------------------------------------------------------------------------- 1 | package algorithm 2 | 3 | //Stack 4 | //author:Xiong Chuan Liang 5 | //date:2015-1-30 6 | 7 | 8 | import ( 9 | "errors" 10 | "fmt" 11 | ) 12 | 13 | 14 | type Stack struct { 15 | Element []interface{} //Element 16 | } 17 | 18 | func NewStack() *Stack { 19 | return &Stack{} 20 | } 21 | 22 | func (stack *Stack)Push(value ...interface{}){ 23 | stack.Element = append(stack.Element,value...) 24 | } 25 | 26 | //返回下一个元素 27 | func (stack *Stack)Top()(value interface{}){ 28 | if stack.Size() > 0 { 29 | return stack.Element[stack.Size() - 1] 30 | } 31 | return nil //read empty stack 32 | } 33 | 34 | //返回下一个元素,并从Stack移除元素 35 | func (stack *Stack)Pop()(err error){ 36 | if stack.Size()> 0 { 37 | stack.Element = stack.Element[:stack.Size() - 1] 38 | return nil 39 | } 40 | return errors.New("Stack为空.") //read empty stack 41 | } 42 | 43 | //交换值 44 | func (stack *Stack)Swap(other *Stack){ 45 | switch{ 46 | case stack.Size() == 0 && other.Size() == 0: 47 | return 48 | case other.Size() == 0 : 49 | other.Element = stack.Element[:stack.Size()] 50 | stack.Element = nil 51 | case stack.Size()== 0 : 52 | stack.Element = other.Element 53 | other.Element = nil 54 | default: 55 | stack.Element,other.Element = other.Element,stack.Element 56 | } 57 | return 58 | } 59 | 60 | //修改指定索引的元素 61 | func (stack *Stack)Set(idx int,value interface{})(err error){ 62 | if idx >= 0 && stack.Size() > 0 && stack.Size() > idx{ 63 | stack.Element[idx] = value 64 | return nil 65 | } 66 | return errors.New("Set失败!") 67 | } 68 | 69 | //返回指定索引的元素 70 | func (stack *Stack)Get(idx int)(value interface{}){ 71 | if idx >= 0 && stack.Size() > 0 && stack.Size() > idx { 72 | return stack.Element[idx] 73 | } 74 | return nil //read empty stack 75 | } 76 | 77 | //Stack的size 78 | func (stack *Stack)Size()(int){ 79 | return len(stack.Element) 80 | } 81 | 82 | //是否为空 83 | func (stack *Stack)Empty()(bool){ 84 | if stack.Element == nil || stack.Size() == 0 { 85 | return true 86 | } 87 | return false 88 | } 89 | 90 | //打印 91 | func (stack *Stack)Print(){ 92 | for i := len(stack.Element) - 1; i >= 0; i--{ 93 | fmt.Println(i,"=>",stack.Element[i]) 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /clcolor/clcolor.go: -------------------------------------------------------------------------------- 1 | package clcolor 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | ) 7 | 8 | const ( 9 | TextBlack = iota + 30 10 | TextRed 11 | TextGreen 12 | TextYellow 13 | TextBlue 14 | TextMagenta 15 | TextCyan 16 | TextWhite 17 | ) 18 | 19 | func Black(str string) string { 20 | return textColor(TextBlack, str) 21 | } 22 | 23 | func Red(str string) string { 24 | return textColor(TextRed, str) 25 | } 26 | 27 | func Green(str string) string { 28 | return textColor(TextGreen, str) 29 | } 30 | 31 | func Yellow(str string) string { 32 | return textColor(TextYellow, str) 33 | } 34 | 35 | func Blue(str string) string { 36 | return textColor(TextBlue, str) 37 | } 38 | 39 | func Magenta(str string) string { 40 | return textColor(TextMagenta, str) 41 | } 42 | 43 | func Cyan(str string) string { 44 | return textColor(TextCyan, str) 45 | } 46 | 47 | func White(str string) string { 48 | return textColor(TextWhite, str) 49 | } 50 | 51 | func textColor(color int, str string) string { 52 | if IsWindows() { 53 | return str 54 | } 55 | 56 | switch color { 57 | case TextBlack: 58 | return fmt.Sprintf("\x1b[0;%dm%s\x1b[0m", TextBlack, str) 59 | case TextRed: 60 | return fmt.Sprintf("\x1b[0;%dm%s\x1b[0m", TextRed, str) 61 | case TextGreen: 62 | return fmt.Sprintf("\x1b[0;%dm%s\x1b[0m", TextGreen, str) 63 | case TextYellow: 64 | return fmt.Sprintf("\x1b[0;%dm%s\x1b[0m", TextYellow, str) 65 | case TextBlue: 66 | return fmt.Sprintf("\x1b[0;%dm%s\x1b[0m", TextBlue, str) 67 | case TextMagenta: 68 | return fmt.Sprintf("\x1b[0;%dm%s\x1b[0m", TextMagenta, str) 69 | case TextCyan: 70 | return fmt.Sprintf("\x1b[0;%dm%s\x1b[0m", TextCyan, str) 71 | case TextWhite: 72 | return fmt.Sprintf("\x1b[0;%dm%s\x1b[0m", TextWhite, str) 73 | default: 74 | return str 75 | } 76 | } 77 | 78 | func IsWindows() bool { 79 | if runtime.GOOS == "windows" { 80 | return true 81 | } else { 82 | return false 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /utils/dtutil.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | "strings" 7 | ) 8 | 9 | func GoStdTime()string{ 10 | return "2006-01-02 15:04:05" 11 | } 12 | 13 | func GoStdUnixDate()string{ 14 | return "Mon Jan _2 15:04:05 MST 2006" 15 | } 16 | 17 | func GoStdRubyDate()string{ 18 | return "Mon Jan 02 15:04:05 -0700 2006" 19 | } 20 | 21 | func GetTmStr(tm time.Time,format string)(string){ 22 | patterns := []string{ 23 | "y","2006", 24 | "m","01", 25 | "d","02", 26 | 27 | "Y","2006", 28 | "M","01", 29 | "D","02", 30 | 31 | "h","03", //12小时制 32 | "H","15", //24小时制 33 | 34 | "i","04", 35 | "s","05", 36 | 37 | "t","pm", 38 | "T","PM", 39 | } 40 | return convStr(tm,format,patterns) 41 | } 42 | 43 | func GetTmShortStr(tm time.Time,format string)(string){ 44 | patterns := []string{ 45 | "y","06", 46 | "m","1", 47 | "d","2", 48 | 49 | "Y","06", 50 | "M","1", 51 | "D","2", 52 | 53 | "h","3", //12小时制 54 | "H","15", //24小时制 55 | 56 | "i","4", 57 | "s","5", 58 | 59 | "t","pm", 60 | "T","PM", 61 | } 62 | 63 | return convStr(tm,format,patterns) 64 | } 65 | 66 | 67 | func convStr(tm time.Time,format string,patterns []string)(string){ 68 | replacer := strings.NewReplacer(patterns...) 69 | strfmt := replacer.Replace(format) 70 | return tm.Format(strfmt) 71 | } 72 | 73 | func GetLocaltimeStr()(string){ 74 | now := time.Now().Local() 75 | year,mon,day := now.Date() 76 | hour,min,sec := now.Clock() 77 | zone,_ := now.Zone() 78 | return fmt.Sprintf("%d-%d-%d %02d:%02d:%02d %s",year,mon,day,hour,min,sec,zone) 79 | } 80 | 81 | func GetGmtimeStr()(string){ 82 | now := time.Now() 83 | year,mon,day := now.UTC().Date() 84 | hour,min,sec := now.UTC().Clock() 85 | zone,_ := now.UTC().Zone() 86 | return fmt.Sprintf("%d-%d-%d %02d:%02d:%02d %s",year,mon,day,hour,min,sec,zone) 87 | } 88 | 89 | func GetUnixTimeStr(ut int64,format string)(string){ 90 | t := time.Unix(ut,0) 91 | return GetTmStr(t,format) 92 | } 93 | 94 | func GetUnixTimeShortStr(ut int64,format string)(string){ 95 | t := time.Unix(ut,0) 96 | return GetTmShortStr(t,format) 97 | } 98 | 99 | func Greatest(arr []time.Time)(time.Time){ 100 | var temp time.Time 101 | for _,at := range arr { 102 | if temp.Before(at) { 103 | temp = at 104 | } 105 | } 106 | return temp; 107 | } 108 | 109 | 110 | type TimeSlice []time.Time 111 | 112 | func (s TimeSlice) Len() int { 113 | return len(s) 114 | } 115 | 116 | func (s TimeSlice) Swap(i, j int) { 117 | s[i], s[j] = s[j], s[i] 118 | } 119 | 120 | func (s TimeSlice) Less(i, j int) bool { 121 | if s[i].IsZero() { 122 | return false 123 | } 124 | if s[j].IsZero() { 125 | return true 126 | } 127 | return s[i].Before(s[j]) 128 | } 129 | 130 | -------------------------------------------------------------------------------- /utils/regutil.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | "regexp" 6 | ) 7 | 8 | func IsIP(str string) bool { 9 | regular := `((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)` 10 | return regexp.MustCompile(regular).MatchString(str) 11 | } 12 | 13 | func IsEmail(str string) bool { 14 | regular := `^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$` 15 | return regexp.MustCompile(regular).MatchString(str) 16 | } 17 | 18 | func IsTelephone(str string) bool { 19 | regular := `^(010|02\d{1}|0[3-9]\d{2})-\d{7,9}(-\d+)?$` 20 | return regexp.MustCompile(regular).MatchString(str) 21 | } 22 | 23 | func Is400(str string) bool { 24 | regular := `^400(-\d{3,4}){2}$` 25 | return regexp.MustCompile(regular).MatchString(str) 26 | 27 | } 28 | 29 | func IsPhone(str string) bool { 30 | regular := `^(\+?86-?)?(18|15|13)[0-9]{9}$` 31 | return regexp.MustCompile(regular).MatchString(str) 32 | } 33 | 34 | func IsYMD(str string) bool { 35 | //(?!0000) 闰年:2016-02-29 36 | regular := `^([0-9]{4}-((0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-8])|(0[13-9]|1[0-2])-(29|30)|(0[13578]|1[02])-31)|([0-9]{2}(0[48]|[2468][048]|[13579][26])|(0[48]|[2468][048]|[13579][26])00)-02-29)$` 37 | return regexp.MustCompile(regular).MatchString(str) 38 | } 39 | 40 | func IsHMS_APM(str string) bool { 41 | //hh:mm:ss xx 42 | regular := `(0[1-9]|1[0-2]):[0-5][0-9]:[0-5][0-9] ([AP]M)` 43 | return regexp.MustCompile(regular).MatchString(str) 44 | } 45 | 46 | func IsHMS(str string) bool { 47 | //hh:mm:ss 48 | regular := `(0[1-9]|1[0-2]):[0-5][0-9]:[0-5][0-9]` 49 | return regexp.MustCompile(regular).MatchString(str) 50 | } 51 | 52 | func IsYMDHMS(str string) bool { 53 | //YYYY-MM-DD 54 | //(?!0000) 闰年:2016-02-29 55 | regular := `^([0-9]{4}-((0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-8])|(0[13-9]|1[0-2])-(29|30)|(0[13578]|1[02])-31)|([0-9]{2}(0[48]|[2468][048]|[13579][26])|(0[48]|[2468][048]|[13579][26])00)-02-29) (0[1-9]|1[0-2]):[0-5][0-9]:[0-5][0-9]$` 56 | return regexp.MustCompile(regular).MatchString(str) 57 | } 58 | 59 | func IsNumber(str string) bool { 60 | //只能输入数字 61 | regular := `^[0-9]*$` 62 | return regexp.MustCompile(regular).MatchString(str) 63 | } 64 | 65 | func IsFloat(str string) bool { 66 | //整数或者小数 67 | regular := `^[0-9]+([.]{0,1}[0-9]+){0,1}$` 68 | return regexp.MustCompile(regular).MatchString(str) 69 | } 70 | 71 | func IsNumber_M_N(str string, m, n int) bool { 72 | //只能输入m-n个数字 73 | regular := fmt.Sprint("^\\d{%d,%d)$", m, n) 74 | return regexp.MustCompile(regular).MatchString(str) 75 | } 76 | 77 | func IsSpecialSymbols(str string) bool { 78 | //特殊符号开头 79 | regular := `^[!@#$%^&*()_+-={}|[]\:";'<>?,./]+` 80 | return regexp.MustCompile(regular).MatchString(str) 81 | } 82 | 83 | func IsChineseCharacter(str string) bool { 84 | //是否全是中文 85 | regular := `^[\u4E00-\u9FA5]+$` 86 | return regexp.MustCompile(regular).MatchString(str) 87 | } 88 | --------------------------------------------------------------------------------