├── README.md ├── base ├── func │ └── main.go └── var │ ├── list.go │ ├── main.go │ └── type.go ├── beego └── logs │ └── main.go ├── chan └── main.go ├── compress ├── main.go └── temp │ ├── c.csv │ └── test.zip ├── conf └── main.go ├── db └── oracle.go ├── dbcon └── main.go ├── encrypt ├── main.go └── test.go ├── exception └── main.go ├── export ├── MyXLSXFile.xlsx ├── excel.go └── excel1.go ├── file ├── main.go ├── read.go └── write.go ├── gc ├── gc.exe ├── main.go └── test.prof ├── gist └── models.tpl ├── goroutine ├── channel.go ├── main.go ├── main1.go ├── main2.go ├── select.go └── sycn.go ├── heap ├── cheap.go └── main.go ├── http ├── httpHelper.go ├── main.go └── main1.go ├── iconv └── main.go ├── inittest ├── main.go └── utils │ └── log.go ├── interface ├── main.go ├── main1.go └── relect-main.go ├── log └── main.go ├── mail └── mail.go ├── net └── main.go ├── plugin └── select.sub ├── rand └── main.go ├── router └── main.go ├── rpc └── htttprpc.go ├── sign └── main.go ├── sms └── main.go ├── socket ├── client.go ├── server-long.go ├── server.go └── server │ ├── main.go │ └── session │ ├── server.go │ └── session.go ├── sort ├── main.go └── test.go ├── srclearn ├── test1.6 └── test1.go ├── textop ├── Server.json ├── Server.xml ├── jsonop.go ├── jsonop2.go ├── regexpop.go ├── template.go ├── templateHelper.go ├── test.xml ├── urlencode.go └── xmlop.go ├── time ├── beego-timer.go ├── main.go └── tasktimer.go ├── tools └── main.go ├── web ├── main.go ├── main1.go ├── mymux.go ├── static │ └── aaa.txt └── web.exe └── zk ├── client.go ├── example └── zkutil.go ├── main.go └── server.go /README.md: -------------------------------------------------------------------------------- 1 | go-learn 2 | ======== 3 | 4 | go语言学习,主要是个人联系杂乱的例子 5 | 6 | 17 | -------------------------------------------------------------------------------- /base/func/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "strings" 7 | ) 8 | 9 | func test1() { 10 | encryptStr := os.Args[1] 11 | if encryptStr == "" { 12 | fmt.Errorf("Error s%", "参数为空") 13 | return 14 | } 15 | fmt.Println(encryptStr) 16 | } 17 | 18 | func test2() { 19 | type Param struct { 20 | Id int64 21 | Name string 22 | } 23 | a := Param{Id: 12, Name: "guojing"} 24 | fmt.Printf("%s\n", a) 25 | fmt.Printf("%+s\n", a) 26 | fmt.Printf("%#s\n", a) 27 | } 28 | 29 | func test3() { 30 | a := []int{1, 2, 3} 31 | b := []int{7, 8, 9} 32 | c := make([]int, len(a)+len(b)) 33 | copy(c, a) 34 | copy(c[len(a):], b) 35 | fmt.Println(c) 36 | } 37 | 38 | func test4() { 39 | a := []int{1, 2, 3} 40 | // b := []int{7, 8, 9} 41 | c := append(a, 3, 4, 5) 42 | fmt.Println(c) 43 | } 44 | 45 | func test5() { 46 | a := []int{1, 2, 3} 47 | fmt.Println(a[1:2]) 48 | } 49 | 50 | func test6() { 51 | str := "aaaa?stageId={stageId}&status={status}" 52 | str = strings.Replace(str, "{stageId}", "11", 1) 53 | str = strings.Replace(str, "{status}", "2", 1) 54 | fmt.Println(str) 55 | } 56 | 57 | func test7() { 58 | str := "asdqwezxctyughjbmnvbn" 59 | a := "c" 60 | index := strings.Index(str, a) 61 | fmt.Print(index) 62 | } 63 | 64 | func main() { 65 | test7() 66 | } 67 | -------------------------------------------------------------------------------- /base/var/list.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "container/list" 5 | "fmt" 6 | ) 7 | 8 | func main() { 9 | a := list.New() 10 | for i := 0; i < 10; i++ { 11 | a.PushBack(i) 12 | fmt.Println(i) 13 | } 14 | fmt.Println(list) 15 | 16 | a.Remove(2) 17 | a.Remove(7) 18 | 19 | for e := a.Front(); e != nil; e.Next() { 20 | fmt.Println(e) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /base/var/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "container/list" 5 | "crypto/rand" 6 | "fmt" 7 | "sort" 8 | "strconv" 9 | "strings" 10 | ) 11 | 12 | func test1() { 13 | s1 := "12" 14 | strconv.ParseInt(s1, 10, 32) 15 | fmt.Println(s1) 16 | } 17 | 18 | func test2() { 19 | alphanum := "0123456789" 20 | var bytes = make([]byte, 3) 21 | rand.Read(bytes) 22 | for i, b := range bytes { 23 | bytes[i] = alphanum[b%byte(len(alphanum))] 24 | fmt.Println(b % byte(len(alphanum))) 25 | } 26 | 27 | fmt.Println(string(bytes)) 28 | } 29 | 30 | func test3() { 31 | var array [5]rune 32 | array[0] = 'a' 33 | array[1] = 'b' 34 | array[2] = 'c' 35 | array[3] = 'd' 36 | array[4] = 'e' 37 | fmt.Println(string(array[0])) 38 | } 39 | 40 | func test4() { 41 | var arr2 *[]int = new([]int) 42 | fmt.Println((*arr2)) 43 | } 44 | 45 | func test5() { 46 | var p []int 47 | fmt.Println(p) 48 | } 49 | 50 | func test6() { 51 | a := "abcdefg" 52 | fmt.Println(a[0:3]) 53 | } 54 | 55 | func test7() { 56 | a := "## \r" 57 | // b := []byte{13} 58 | fmt.Println([]byte(a)) 59 | } 60 | 61 | func test8() { 62 | a := map[int32]int32{1: 1, 2: 2, 3: 3, 4: 4} 63 | fmt.Println(len(a)) 64 | fmt.Println(a) 65 | } 66 | func test9() { 67 | a := []int32{1, 2, 3, 4, 5, 6} 68 | for i, b := range a { 69 | fmt.Println(i, b) 70 | } 71 | } 72 | 73 | func test10() { 74 | a := map[int32]int32{1: 1, 2: 2, 3: 3, 4: 4} 75 | for key, value := range a { 76 | fmt.Println(key, value) 77 | if key == 3 { 78 | delete(a, key) 79 | } 80 | } 81 | 82 | fmt.Println(a) 83 | } 84 | 85 | func test11() { 86 | a := 10 87 | for a > 0 { 88 | a-- 89 | fmt.Println(a) 90 | } 91 | } 92 | 93 | func test12() { 94 | a := "abcdef" 95 | fmt.Println(strings.Index(a, "c")) 96 | 97 | fmt.Println(strings.Repeat(a, 10)) 98 | } 99 | 100 | func test13() { 101 | a := make(map[int]int) 102 | for i := 1; i < 10; i++ { 103 | a[i] = i 104 | } 105 | 106 | for key, value := range a { 107 | fmt.Println(key, value) 108 | } 109 | } 110 | 111 | func test14() { 112 | a := make([]int, 0) 113 | a = append(a, 1) 114 | a = append(a, 2) 115 | a = append(a, 3) 116 | a = append(a, 4) 117 | a = append(a, 5) 118 | a = append(a, 6) 119 | 120 | // j := len(a) 121 | // for i := 0; i < j; i++ { 122 | // a = a[1:] 123 | // fmt.Println(a) 124 | // } 125 | 126 | for _, value := range a { 127 | fmt.Println(value) 128 | a = a[1:] 129 | } 130 | 131 | fmt.Println(a) 132 | } 133 | 134 | type Order struct { 135 | OrderId int64 //订单号 136 | } 137 | 138 | func test15() { 139 | orderlist := list.New() 140 | order1 := &Order{OrderId: 1} 141 | order2 := &Order{OrderId: 2} 142 | order3 := &Order{OrderId: 3} 143 | order4 := &Order{OrderId: 4} 144 | order5 := &Order{OrderId: 5} 145 | orderlist.PushBack(*order1) 146 | orderlist.PushBack(*order2) 147 | orderlist.PushBack(*order3) 148 | orderlist.PushBack(*order4) 149 | orderlist.PushBack(*order5) 150 | eachList(orderlist) 151 | 152 | for elem := orderlist.Front(); elem != nil; { 153 | fmt.Println("-------------------") 154 | order := elem.Value.(Order) 155 | if order.OrderId == 3 { 156 | elem = deleteOrder(orderlist, elem) 157 | } else { 158 | elem = elem.Next() 159 | } 160 | eachList(orderlist) 161 | } 162 | } 163 | 164 | func deleteOrder(orderList *list.List, elem *list.Element) (nextElem *list.Element) { 165 | nextElem = elem.Next() 166 | orderList.Remove(elem) 167 | return 168 | } 169 | 170 | func eachList(orderList *list.List) { 171 | for elem := orderList.Front(); elem != nil; elem = elem.Next() { 172 | order := elem.Value.(Order) 173 | fmt.Println(order.OrderId) 174 | } 175 | } 176 | 177 | func test16() { 178 | a := []string{"1", "2", "3"} 179 | b := []string{"3", "4", "5"} 180 | copy(a, b) 181 | fmt.Println(a) 182 | } 183 | 184 | func test17() { 185 | filePath := "/home/wwwlogs/productlogs/ubox002/service/exception.2014-05-11.log" 186 | index := strings.LastIndex(filePath, "/") 187 | if index > 1 { 188 | prePath := filePath[:index-1] 189 | index = strings.LastIndex(prePath, "/") 190 | prePath = prePath[index+1:] 191 | fmt.Println(prePath) 192 | } 193 | } 194 | 195 | type OrderList struct { 196 | Orders map[int64][]*Order 197 | } 198 | 199 | type Test1 struct { 200 | Name string 201 | } 202 | 203 | func test19() { 204 | a := []string{"aaa", "bbb"} 205 | test1 := &Test1{ 206 | Name: a[1], 207 | } 208 | a = nil 209 | fmt.Println(test1.Name) 210 | } 211 | 212 | type OrderList1 struct { 213 | Orders map[string][3]float32 214 | } 215 | 216 | func test20() { 217 | a := make(map[string]*[3]float32, 0) 218 | v1 := [3]float32{0.05, 0.06, 13} 219 | v2 := [3]float32{0.05, 0.06, 13} 220 | v3 := [3]float32{0.05, 0.06, 13} 221 | a["v1"] = &v1 222 | a["v2"] = &v2 223 | a["v3"] = &v3 224 | 225 | p := a["v1"] 226 | p[1] = 0.09 227 | fmt.Println(a["v1"][1]) 228 | } 229 | 230 | func test21(a map[string]string) { 231 | a["aaa"] = "bbbb" 232 | } 233 | 234 | func test22() { 235 | a := make(map[string]string, 0) 236 | a["aaa"] = "tttt" 237 | fmt.Println(a) 238 | test21(a) 239 | fmt.Println(a) 240 | } 241 | 242 | func test23() { 243 | var a float32 244 | a = 0.649 245 | a = a * 1000 246 | value := strconv.FormatFloat(float64(a), 'f', 0, 32) 247 | fmt.Println(strconv.Atoi(value)) 248 | } 249 | 250 | func test24() { 251 | str := `'%%,%s,%%'` 252 | fmt.Println(fmt.Sprintf(str, "aaa")) 253 | } 254 | 255 | func test25() { 256 | str := `%X` 257 | fmt.Println(fmt.Sprintf(str, "aaa")) 258 | } 259 | 260 | func test26(format string, v ...interface{}) string { 261 | return fmt.Sprintf("[I] "+format, v...) 262 | 263 | } 264 | 265 | func test27() { 266 | fmt.Println(test26("logger initialized.%v", "aaaa")) 267 | } 268 | 269 | func test28(a []int) { 270 | a[2] = 10 271 | } 272 | 273 | func test29() { 274 | a := []int{1, 3, 4} 275 | test28(a) 276 | fmt.Println(a) 277 | } 278 | 279 | func test30() { 280 | url := "http://localhost:8081/test?token=gAGLi003OC3qKpRYCOq2clzYCuh5tt5hkXJppkwVZeE=" 281 | index := strings.Index(url, "token=") 282 | index = index + 6 283 | fmt.Println(url[:index]) 284 | } 285 | 286 | func test31() { 287 | a := make([]int, 3) 288 | b := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 289 | fmt.Println(len(a), cap(a)) 290 | fmt.Printf("%p\n", &a) 291 | a = append(a, b...) 292 | fmt.Println(len(a), cap(a)) 293 | fmt.Printf("%p\n", &a) 294 | 295 | } 296 | 297 | func test32(a []int) { 298 | a[1] = 10 299 | } 300 | func test33() { 301 | a := []int{1, 2, 3, 4, 5} 302 | test32(a[:2]) 303 | fmt.Println(a) 304 | } 305 | 306 | func test34() { 307 | a := "4.9E-324" 308 | b, err := strconv.ParseFloat(a, 64) 309 | if err != nil { 310 | fmt.Println(err.Error()) 311 | } 312 | fmt.Println(b) 313 | } 314 | 315 | func test35() { 316 | a := []int{1, 2, 3, 4, 5} 317 | fmt.Println(len(a[1:3])) 318 | } 319 | 320 | func test36() { 321 | var a float64 322 | a = 116.4807858 323 | b := strconv.FormatFloat(a, 'f', 6, 64) 324 | fmt.Println(b) 325 | } 326 | 327 | func test37() { 328 | a := []float64{116.480604, 116.481032, 116.480623, 116.480581, 116.481066, 116.481131, 116.480604} 329 | sort.Float64s(a) 330 | fmt.Println(a) 331 | } 332 | 333 | func test39() { 334 | a := 10 335 | for a > 0 { 336 | fmt.Println(a) 337 | a-- 338 | } 339 | } 340 | 341 | func test40() { 342 | a := float64(5E-324) 343 | fmt.Println(a == 4.9E-324) 344 | } 345 | func test41() { 346 | a := []string{"a"} 347 | fmt.Println(a, strings.Join(a, ",")) 348 | } 349 | 350 | func test42() { 351 | var a float64 352 | a = 0.0209615616 353 | val := strconv.FormatFloat(a, 'f', 4, 64) 354 | a, _ = strconv.ParseFloat(val, 64) 355 | fmt.Println(a) 356 | } 357 | 358 | func test43() { 359 | a := map[string]string{"aa": "ddd", "bb": "ccc"} 360 | b := a["rr"] 361 | fmt.Println(b == "") 362 | } 363 | 364 | func test44() { 365 | a := "1,2" 366 | b := strings.Split(a, ",") 367 | fmt.Println(b) 368 | } 369 | 370 | func test45() { 371 | a := 200 372 | b := float64(a) / 100 373 | c := strconv.FormatFloat(b, 'f', 2, 64) 374 | fmt.Println(c) 375 | } 376 | 377 | func test47() { 378 | a := make([][]string, 0) 379 | b := []string{"a", "b", "c", "d"} 380 | // c := []string{"a", "b", "c", "d"} 381 | // d := []string{"a", "b", "c", "d"} 382 | a = append(a, b) 383 | a = append(a, b) 384 | a = append(a, b) 385 | } 386 | 387 | func test46() { 388 | // a := []byte{0, 0, 0} 389 | // m := make(map[[]byte]string, 0) 390 | 391 | // m[a] = "aaa" 392 | 393 | // fmt.Println(m[a]) 394 | } 395 | 396 | func test50() { 397 | // a := make([]int, 0) 398 | // a = append(a, 1) 399 | // a = append(a, 2) 400 | // fmt.Println(a) 401 | } 402 | 403 | func test48() { 404 | // fmt.Println(strings.Replace("temp/1231231231.zip", "temp/", new, n)) 405 | } 406 | 407 | func test49() { 408 | a := []string{"a", "b", "c"} 409 | b := []string{"d", "e"} 410 | a = append(a, b...) 411 | fmt.Println(a) 412 | } 413 | 414 | type TElem struct { 415 | name string 416 | id int64 417 | } 418 | 419 | func test51() { 420 | t1 := &TElem{"gj", 0} 421 | t2 := &TElem{"gj1", 1} 422 | 423 | a := make([]*TElem, 2) 424 | a[0] = t1 425 | a[1] = t2 426 | 427 | t3 := &TElem{"gj2", 2} 428 | a = append(a, t3) 429 | a[2].name = "gj3" 430 | fmt.Println(t3.name) 431 | } 432 | 433 | func test52() { 434 | t1 := &TElem{"gj", 0} 435 | t2 := &TElem{"gj1", 1} 436 | 437 | a := make([]*TElem, 2) 438 | a[0] = t1 439 | a[1] = t2 440 | 441 | t3 := &TElem{"gj2", 2} 442 | b := make([]*TElem, 1) 443 | b[0] = t3 444 | 445 | temp := make([]*TElem, 3) 446 | copy(temp, a) 447 | copy(temp[len(a):], b) 448 | 449 | temp[2].name = "gj3" 450 | fmt.Println(b[0].name) 451 | <<<<<<< HEAD 452 | } 453 | 454 | func main() { 455 | test52() 456 | ======= 457 | } 458 | 459 | func test53() { 460 | a := ",guoj," 461 | fmt.Println(a[1 : len(a)-1]) 462 | } 463 | 464 | func test54() { 465 | type T struct { 466 | Name string 467 | Age int64 468 | } 469 | 470 | t1 := &T{Name: "gj", Age: 12} 471 | 472 | t2 := new(T) 473 | t2.Name = "gj2" 474 | t2.Age = 13 475 | 476 | t3 := T{Name: "gj3", Age: 14} 477 | fmt.Println(&t1, t2.Name, &t3) 478 | } 479 | 480 | func main() { 481 | test54() 482 | >>>>>>> c6254d3cc19aeaedeac31f84f04c473c4ff6d83b 483 | } 484 | -------------------------------------------------------------------------------- /base/var/type.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | /* 8 | 128: 1000 0000 9 | 1<<10:100 0000 0000 10 | */ 11 | 12 | type ApiHead struct { 13 | Code int `json:"code"` 14 | Msg string `json:"msg,omitempty"` 15 | Desc string `json:"desc,omitempty"` 16 | } 17 | 18 | func test1() { 19 | fmt.Println(128 & (1 << uint(10))) 20 | } 21 | 22 | func test2() { 23 | datas := make([]map[string]interface{}, 10) 24 | fmt.Println(datas) 25 | } 26 | 27 | func test4(msg interface{}) { 28 | 29 | } 30 | func test5() { 31 | var flt float64 32 | var i int64 33 | flt = 0.23544645 * 100 34 | i = int64(flt) 35 | fmt.Println(i) 36 | } 37 | 38 | func main() { 39 | test5() 40 | } 41 | -------------------------------------------------------------------------------- /beego/logs/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/astaxie/beego/httplib" 6 | ) 7 | 8 | // 响应数据结构 9 | type ApiResp struct { 10 | Head ApiHead `json:"head"` 11 | Body interface{} `json:"body,omitempty"` 12 | } 13 | 14 | // 响应头结构 15 | type ApiHead struct { 16 | Code int `json:"code"` 17 | Msg string `json:"msg"` 18 | } 19 | 20 | func test2() { 21 | req := httplib.Get("http://localhost:8081/test") 22 | httpRes, _ := req.Response() 23 | fmt.Println(httpRes.StatusCode) 24 | 25 | result := &ApiResp{} 26 | err := req.ToJson(result) 27 | fmt.Println(err) 28 | fmt.Println(result) 29 | } 30 | 31 | func main() { 32 | test2() 33 | } 34 | -------------------------------------------------------------------------------- /chan/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | "time" 7 | ) 8 | 9 | var ChanMap map[string]chan bool 10 | 11 | func ReciveMsg() { 12 | time.Sleep(time.Second * 10) 13 | a := ChanMap["0001"] 14 | a <- true 15 | } 16 | 17 | func test1() { 18 | ChanMap = make(map[string]chan bool) 19 | a := make(chan bool, 1) 20 | ChanMap["0001"] = a 21 | go ReciveMsg() 22 | b := <-a 23 | fmt.Println("recive:", b) 24 | } 25 | 26 | func test2(b chan bool) { 27 | a := 0 28 | for { 29 | if a > 3 { 30 | break 31 | } 32 | select { 33 | case <-time.After(time.Second * 3): 34 | fmt.Println(a) 35 | a++ 36 | } 37 | } 38 | fmt.Println("aaaa") 39 | b <- true 40 | } 41 | 42 | func test3() { 43 | b := make(chan int) 44 | // b<-"testing" 45 | close(b) 46 | fmt.Println(b) 47 | // b<-"testing2" 48 | // fmt.Println("aaaa") 49 | } 50 | 51 | func test4() { 52 | b := make(chan string, 1) 53 | b <- "testing1" 54 | close(b) 55 | fmt.Println(<-b) 56 | b = make(chan string, 1) 57 | b <- "testing2" 58 | fmt.Println(<-b) 59 | } 60 | 61 | // func test5() { 62 | // b := make(chan int) 63 | // b <- "testing" 64 | // close(b) 65 | // if c, ok := <-b; ok { 66 | // fmt.Println(b) 67 | // } 68 | // } 69 | 70 | func test6() { 71 | runtime.GOMAXPROCS(4) 72 | ch := make(chan int, 3) 73 | go func() { 74 | fmt.Print("3") 75 | time.Sleep(20 * time.Second) 76 | }() 77 | fmt.Print("1") 78 | <-ch 79 | fmt.Print("2") 80 | } 81 | 82 | func main() { 83 | test6() 84 | } 85 | -------------------------------------------------------------------------------- /compress/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "archive/zip" 5 | "errors" 6 | "io" 7 | "os" 8 | "strings" 9 | ) 10 | 11 | const ( 12 | singleFileByteLimit = 107374182400 // 1 GB 13 | chunkSize = 4096 // 4 KB 14 | ) 15 | 16 | func copyContents(r io.Reader, w io.Writer) error { 17 | var size int64 18 | b := make([]byte, chunkSize) 19 | for { 20 | // we limit the size to avoid zip bombs 21 | size += chunkSize 22 | if size > singleFileByteLimit { 23 | return errors.New("file too large, please contact us for assistance") 24 | } 25 | // read chunk into memory 26 | length, err := r.Read(b[:cap(b)]) 27 | if err != nil { 28 | if err != io.EOF { 29 | return err 30 | } 31 | if length == 0 { 32 | break 33 | } 34 | } 35 | // write chunk to zip file 36 | _, err = w.Write(b[:length]) 37 | if err != nil { 38 | return err 39 | } 40 | } 41 | return nil 42 | } 43 | 44 | /** 45 | * 写 46 | */ 47 | func test1() { 48 | target := "temp/test.zip" 49 | sources := make([]string, 2) 50 | sources[0] = "temp/a.csv" 51 | sources[1] = "temp/b.csv" 52 | 53 | fw, _ := os.Create(target) 54 | defer fw.Close() 55 | 56 | wt := zip.NewWriter(fw) 57 | defer wt.Close() 58 | 59 | for _, source := range sources { 60 | index := strings.LastIndex(source, "/") 61 | fileName := source[index+1:] 62 | w, _ := wt.Create(fileName) 63 | rf, _ := os.Open(source) 64 | copyContents(rf, w) 65 | rf.Close() 66 | os.Remove(source) 67 | } 68 | } 69 | 70 | /** 71 | * 添加 72 | */ 73 | func test2() { 74 | target := "temp/test.zip" 75 | sources := make([]string, 2) 76 | sources[0] = "temp/a.log" 77 | sources[0] = "temp/b.log" 78 | 79 | fw, _ := os.Create(target) 80 | defer fw.Close() 81 | 82 | wt := zip.NewWriter(fw) 83 | defer wt.Close() 84 | 85 | for _, source := range sources { 86 | index := strings.LastIndex(source, "/") 87 | fileName := source[index+1:] 88 | w, _ := wt.Create(fileName) 89 | rf, _ := os.Open(source) 90 | copyContents(rf, w) 91 | rf.Close() 92 | // os.Remove(source) 93 | } 94 | } 95 | 96 | func main() { 97 | test2() 98 | } 99 | -------------------------------------------------------------------------------- /compress/temp/c.csv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NotBadPad/go-learn/2866261cfa181c2b33815d46de3da948f2d06daa/compress/temp/c.csv -------------------------------------------------------------------------------- /compress/temp/test.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NotBadPad/go-learn/2866261cfa181c2b33815d46de3da948f2d06daa/compress/temp/test.zip -------------------------------------------------------------------------------- /conf/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/astaxie/beego" 6 | ) 7 | 8 | func main() { 9 | fmt.Println("aaa", beego.LevelDebug) 10 | } 11 | -------------------------------------------------------------------------------- /db/oracle.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "database/sql" 5 | "fmt" 6 | _ "github.com/mattn/go-oci8" 7 | ) 8 | 9 | func commitTest() { 10 | // 用户名/密码@实例名 跟sqlplus的conn命令类似 11 | db, err := sql.Open("oci8", "cms_master/cms_master@192.168.8.72:1522/orcl?autocommit=true&charset=utf8") 12 | if err != nil { 13 | fmt.Println(err) 14 | } 15 | defer db.Close() 16 | 17 | tx, err := db.Begin() 18 | if err != nil { 19 | fmt.Println(err) 20 | } 21 | 22 | _, err = tx.Exec("update MT_NODE set DIMENSIONS=39.038853 where NODE_ID=25") 23 | if err != nil { 24 | fmt.Println(err) 25 | } 26 | 27 | _, err = tx.Exec("update MT_NODE set DIMENSIONS=39.075739 where NODE_ID=26") 28 | if err != nil { 29 | fmt.Println(err) 30 | } 31 | 32 | _, err = tx.Exec("update MT_NODE set DIMENSIONS=39.075739 where NODE_ID=29") 33 | if err != nil { 34 | fmt.Println(err) 35 | } 36 | 37 | err = tx.Commit() 38 | if err != nil { 39 | fmt.Println(err) 40 | } 41 | return 42 | } 43 | 44 | func main() { 45 | commitTest() 46 | } 47 | -------------------------------------------------------------------------------- /dbcon/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "database/sql" 5 | "fmt" 6 | _ "github.com/go-sql-driver/mysql" 7 | ) 8 | 9 | func OpenMysql() (db *sql.DB, err error) { 10 | db, err = sql.Open("mysql", `ubox_report:vG6ke8di3bWopRP3fCb6@tcp(211.151.164.45:3307)/ubox_alipaycs?autocommit=true&charset=utf8`) 11 | if db != nil { 12 | db.SetMaxIdleConns(10) 13 | db.SetMaxOpenConns(10) 14 | } 15 | return 16 | } 17 | 18 | func main() { 19 | defer func() { 20 | if x := recover(); x != nil { 21 | fmt.Printf("Error panic: %v\n", x) 22 | } 23 | }() 24 | 25 | db, err := OpenMysql() 26 | if err != nil { 27 | fmt.Println("aaaa" + err.Error()) 28 | } 29 | 30 | count := 0 31 | 32 | sql_ := `SELECT COUNT(0) FROM ub_alipaycs_cancel` 33 | stmt, err := db.Prepare(sql_) 34 | if err != nil { 35 | fmt.Printf("Error exec sql: %s\n", err.Error()) 36 | return 37 | } 38 | defer stmt.Close() 39 | 40 | if err = stmt.QueryRow().Scan(&count); err != nil { 41 | fmt.Printf("Error exec sql: %s\n", err.Error()) 42 | } 43 | 44 | fmt.Println(count) 45 | db.Close() 46 | } 47 | -------------------------------------------------------------------------------- /encrypt/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "crypto/md5" 6 | "crypto/sha1" 7 | "encoding/base64" 8 | "encoding/hex" 9 | "fmt" 10 | "net/url" 11 | "sort" 12 | // "strconv" 13 | // "strings" 14 | "time" 15 | // "os" 16 | ) 17 | 18 | func test1(str string) { 19 | pbytes := []byte(str) 20 | bytes := make([]byte, len(pbytes)) 21 | for i, b := range pbytes { 22 | bytes[i] = b ^ 3 23 | } 24 | pwd := string(bytes) 25 | 26 | fmt.Println(pwd) 27 | } 28 | 29 | func test2() { 30 | var a [2]int 31 | fmt.Println(a[0] ^ a[1]) 32 | } 33 | 34 | func test3() { 35 | str := "awayyqwe123" 36 | enStr := base64.StdEncoding.EncodeToString([]byte(str)) 37 | fmt.Println(enStr) 38 | deStr, _ := base64.StdEncoding.DecodeString(enStr) 39 | fmt.Println(string(deStr)) 40 | } 41 | 42 | func test4() { 43 | str := "daaaf542add66503eb8ae271a4d4eb32" 44 | h := md5.New() 45 | h.Write([]byte(str)) 46 | fmt.Println(hex.EncodeToString(h.Sum(nil))) 47 | } 48 | 49 | func GenerateMsg(kwargs map[string]string) string { 50 | if kwargs == nil { 51 | return "" 52 | } 53 | var buf bytes.Buffer 54 | keys := make([]string, 0, len(kwargs)) 55 | for _, v := range kwargs { 56 | fmt.Println(v) 57 | keys = append(keys, v) 58 | } 59 | sort.Strings(keys) //按key ascii 顺序排序 60 | for _, v := range keys { 61 | buf.WriteString(url.QueryEscape(v)) 62 | } 63 | // beego.Debug(buf.String()) 64 | //做sha1处理,取出16进制全小写字符串 65 | msg := buf.String() 66 | h := sha1.New() 67 | h.Write([]byte(msg)) 68 | bs := h.Sum(nil) 69 | mySign := fmt.Sprintf("%x", bs) 70 | return mySign 71 | } 72 | 73 | func signCheck() { 74 | params := make(map[string]string, 0) 75 | nowTime := time.Now().Unix() 76 | fmt.Println(nowTime) 77 | params["timestamp"] = "1419739624" 78 | params["token"] = "CQN029CBHHhJOQc1OX8VOyaEqFSk9RinGQ" 79 | params["app"] = "5" 80 | val := GenerateMsg(params) 81 | 82 | fmt.Println(val) 83 | } 84 | 85 | func main() { 86 | // if len(os.Args) < 2 { 87 | // fmt.Println("Error 参数为空") 88 | // return 89 | // } 90 | // encryptStr := os.Args[1] 91 | signCheck() 92 | } 93 | -------------------------------------------------------------------------------- /encrypt/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "crypto/sha1" 6 | "fmt" 7 | "net/url" 8 | "sort" 9 | ) 10 | 11 | /** 12 | * 获取微信验签 13 | * 算法:参数值按ascii顺序排序拼接,做sha1 14 | */ 15 | func GenerateWeiXinSign(kwargs map[string]string) string { 16 | if kwargs == nil { 17 | return "" 18 | } 19 | var buf bytes.Buffer 20 | keys := make([]string, 0, len(kwargs)) 21 | for _, v := range kwargs { 22 | keys = append(keys, v) 23 | } 24 | sort.Strings(keys) //按key ascii 顺序排序 25 | for _, v := range keys { 26 | buf.WriteString(url.QueryEscape(v)) 27 | } 28 | // beego.Debug(buf.String()) 29 | //做sha1处理,取出16进制全小写字符串 30 | msg := buf.String() 31 | h := sha1.New() 32 | h.Write([]byte(msg)) 33 | bs := h.Sum(nil) 34 | mySign := fmt.Sprintf("%x", bs) 35 | return mySign 36 | } 37 | 38 | func main() { 39 | params := make(map[string]string, 0) 40 | params["timestamp"] = "1448439054" 41 | params["token"] = "CQN029CBHHhJOQc1OX8VOyaEqFSk9RinGQ" 42 | params["app"] = "5" 43 | 44 | sign := GenerateWeiXinSign(params) 45 | fmt.Println(sign) 46 | } 47 | -------------------------------------------------------------------------------- /exception/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func test() { 4 | defer func() { 5 | if x := recover(); x != nil { 6 | res.Head.Code = HANDLE_ERR 7 | res.Head.Desc = "服务器错误" 8 | beego.Error("error: ", session, x) 9 | } 10 | }() 11 | } 12 | -------------------------------------------------------------------------------- /export/MyXLSXFile.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NotBadPad/go-learn/2866261cfa181c2b33815d46de3da948f2d06daa/export/MyXLSXFile.xlsx -------------------------------------------------------------------------------- /export/excel.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | iconv "github.com/djimenez/iconv-go" 7 | ) 8 | 9 | /** 10 | * 导出处理 11 | */ 12 | 13 | const ( 14 | OUT_ENCODING = "gbk" //输出编码 15 | ) 16 | 17 | /** 18 | * 导出csv格式文件,输出byte数组 19 | * 输出编码通过OUT_ENCODING指定 20 | */ 21 | func ExportCsv(head []string, data [][]string) (out []byte, err error) { 22 | if len(head) == 0 { 23 | err = errors.New("ExportCsv Head is nil") 24 | return 25 | } 26 | 27 | columnCount := len(head) 28 | dataStr := bytes.NewBufferString("") 29 | //添加头 30 | for index, headElem := range head { 31 | separate := "," 32 | if index == columnCount-1 { 33 | separate = "\n" 34 | } 35 | dataStr.WriteString(headElem + separate) 36 | } 37 | 38 | //添加数据行 39 | for _, dataArray := range data { 40 | if len(dataArray) != columnCount { //数据项数小于列数 41 | err = errors.New("ExportCsv data format is error.") 42 | } 43 | for index, dataElem := range dataArray { 44 | separate := "," 45 | if index == columnCount-1 { 46 | separate = "\n" 47 | } 48 | dataStr.WriteString(dataElem + separate) 49 | } 50 | } 51 | 52 | //处理编码 53 | out = make([]byte, len(dataStr.Bytes())) 54 | iconv.Convert(dataStr.Bytes(), out, "utf-8", OUT_ENCODING) 55 | return 56 | } 57 | -------------------------------------------------------------------------------- /export/excel1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/tealeg/xlsx" 6 | ) 7 | 8 | func test1() { 9 | var file *xlsx.File 10 | var sheet *xlsx.Sheet 11 | var row *xlsx.Row 12 | var cell *xlsx.Cell 13 | var err error 14 | 15 | file = xlsx.NewFile() 16 | sheet = file.AddSheet("Sheet1") 17 | row = sheet.AddRow() 18 | cell = row.AddCell() 19 | cell.Value = "000101" 20 | cell = row.AddCell() 21 | cell.Value = "中文" 22 | err = file.Save("MyXLSXFile.xlsx") 23 | if err != nil { 24 | fmt.Printf(err.Error()) 25 | } 26 | } 27 | 28 | func test2() { 29 | var file *xlsx.File 30 | var sheet *xlsx.Sheet 31 | var row *xlsx.Row 32 | var cell *xlsx.Cell 33 | var err error 34 | 35 | file, _ = xlsx.OpenFile("MyXLSXFile.xlsx") 36 | sheet = file.Sheet["Sheet1"] 37 | row = sheet.AddRow() 38 | cell = row.AddCell() 39 | cell.Value = "000101" 40 | cell = row.AddCell() 41 | cell.Value = "中文1" 42 | err = file.Save("MyXLSXFile1.xlsx") 43 | if err != nil { 44 | fmt.Printf(err.Error()) 45 | } 46 | } 47 | 48 | func main() { 49 | test1() 50 | test2() 51 | } 52 | -------------------------------------------------------------------------------- /file/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "path" 6 | "runtime" 7 | ) 8 | 9 | func test1() { 10 | fmt.Println(path.Split(`test/aa/file.css`)) 11 | } 12 | 13 | func test2() { 14 | _, file, line, ok := runtime.Caller(3) 15 | fmt.Println(file) 16 | fmt.Println(line) 17 | fmt.Println(ok) 18 | } 19 | 20 | func main() { 21 | test2() 22 | } 23 | -------------------------------------------------------------------------------- /file/read.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "fmt" 7 | "os" 8 | "time" 9 | ) 10 | 11 | func ReadFile(pathStr string) { 12 | file, err := os.Open(pathStr) 13 | if err != nil { 14 | fmt.Errorf("Error Read file %s: %s\n", pathStr, err.Error()) 15 | } 16 | defer file.Close() 17 | fb := bufio.NewReader(file) 18 | buff := bytes.NewBuffer(make([]byte, 2048)) 19 | count := 0 20 | for { 21 | line, isPrefix, err := fb.ReadLine() 22 | if err != nil { //结束 23 | fmt.Println(count) 24 | break 25 | } 26 | buff.Write(line) 27 | if !isPrefix { //如果前缀标记是false,则说明读取的是整行 28 | buff.String() 29 | buff.Reset() //读取后重置缓冲区 30 | 31 | //处理数据 32 | count++ 33 | } 34 | } 35 | } 36 | 37 | func main() { 38 | begin := time.Now().UnixNano() 39 | strStr := "E:\\workspace\\go\\src\\logstatistics\\temp\\v.ubox.cn\\v.ubox.cn.2014-05-11.log" 40 | ReadFile(strStr) 41 | end := time.Now().UnixNano() 42 | fmt.Println(end - begin) 43 | } 44 | 45 | /** 46 | * 16.9M 47 | * 62035行 48 | * 48ms 49 | * 50 | * 794M 51 | * 2257557行 52 | * 9269ms 53 | * 54 | * 1842M 55 | * 6337175行 56 | * 14181ms 57 | */ 58 | -------------------------------------------------------------------------------- /file/write.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "time" 8 | ) 9 | 10 | const ( 11 | TEST_STR = `Stat returns the FileInfo structure describing file. If there is an error, it will be of type *PathError.\n\r` 12 | LINE_COUNT = 10000000 13 | ) 14 | 15 | func WriteFile(pathStr string) { 16 | file, err := os.Create(pathStr) 17 | if err != nil { 18 | fmt.Errorf("Error create file:%s", err.Error()) 19 | } 20 | defer file.Close() 21 | for i := 0; i < LINE_COUNT; i++ { 22 | file.WriteString(TEST_STR) 23 | } 24 | } 25 | 26 | func WriteFile1(pathStr string) { 27 | file, err := os.Create(pathStr) 28 | if err != nil { 29 | fmt.Errorf("Error Read file %s: %s\n", pathStr, err.Error()) 30 | } 31 | defer file.Close() 32 | fb := bufio.NewWriter(file) 33 | for i := 0; i < LINE_COUNT; i++ { 34 | fb.WriteString(TEST_STR) 35 | } 36 | } 37 | 38 | func main() { 39 | begin := time.Now().UnixNano() 40 | pathStr := "E:/workspace/go/src/go-learn/temp/test2.txt" 41 | WriteFile(pathStr) 42 | end := time.Now().UnixNano() 43 | fmt.Println(end - begin) 44 | 45 | begin = time.Now().UnixNano() 46 | pathStr = "E:/workspace/go/src/go-learn/temp/test3.txt" 47 | WriteFile1(pathStr) 48 | end = time.Now().UnixNano() 49 | fmt.Println(end - begin) 50 | } 51 | -------------------------------------------------------------------------------- /gc/gc.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NotBadPad/go-learn/2866261cfa181c2b33815d46de3da948f2d06daa/gc/gc.exe -------------------------------------------------------------------------------- /gc/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "runtime/pprof" 7 | "time" 8 | ) 9 | 10 | func test1() { 11 | for i := 0; i < 10; i++ { 12 | list := make([]string, 0) 13 | for i := 0; i < 1000; i++ { 14 | list = append(list, `The GOMAXPROCS variable limits the number of operating system threads that can execute user-level Go code simultaneously. There is no limit to the number of threads that can be blocked in system calls on behalf of Go code; those do not count against the GOMAXPROCS limit. This package's GOMAXPROCS function queries and changes the limit. `) 15 | } 16 | // time.Sleep(10 * time.Second) 17 | } 18 | } 19 | 20 | func test2() { 21 | list := make([]string, 100000) 22 | for i := 0; i < 10; i++ { 23 | for i := 0; i < 100000; i++ { 24 | list[i] = `The GOMAXPROCS variable limits the number of operating system threads that can execute user-level Go code simultaneously. There is no limit to the number of threads that can be blocked in system calls on behalf of Go code; those do not count against the GOMAXPROCS limit. This package's GOMAXPROCS function queries and changes the limit. ` 25 | } 26 | time.Sleep(1 * time.Second) 27 | } 28 | } 29 | 30 | func main() { 31 | f, err := os.Create("test.prof") 32 | if err != nil { 33 | log.Print(err.Error()) 34 | return 35 | } 36 | 37 | defer f.Close() 38 | 39 | pprof.StartCPUProfile(f) 40 | defer pprof.StopCPUProfile() 41 | test2() 42 | } 43 | -------------------------------------------------------------------------------- /gc/test.prof: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NotBadPad/go-learn/2866261cfa181c2b33815d46de3da948f2d06daa/gc/test.prof -------------------------------------------------------------------------------- /gist/models.tpl: -------------------------------------------------------------------------------- 1 | /** 2 | * [注释] 3 | */ 4 | func FuncName(/*{参数}*/) (/*{返回值}*/, err error) { 5 | sql_ := `` 6 | stmt, err := utils.DB.Prepare(sql_) 7 | if err != nil { 8 | fmt.Println("Error prepare sql:", err.Error()) 9 | return 10 | } 11 | defer stmt.Close() 12 | 13 | if err = stmt.QueryRow(/*{参数}*/).Scan(/*{赋值}*/); err != nil { 14 | fmt.Println("GetVmInfo Error:", vmCode, err.Error()) 15 | return 16 | } 17 | return 18 | } 19 | 20 | 21 | -------------------------------------------------------------------------------- /goroutine/channel.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func sum(a []int, c chan int) { 6 | total := 0 7 | for _, v := range a { 8 | total += v 9 | } 10 | c <- total 11 | } 12 | 13 | func main() { 14 | a := []int{6, 7, 3, 2, 4, 1, -2, 10} 15 | c := make(chan int) 16 | go sum(a, c) 17 | 18 | result := <-c 19 | 20 | fmt.Println(result) 21 | } 22 | -------------------------------------------------------------------------------- /goroutine/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | "time" 7 | ) 8 | 9 | func say(s string) { 10 | for i := 0; i < 5; i++ { 11 | runtime.Gosched() 12 | fmt.Println("aaaa ", s) 13 | } 14 | } 15 | 16 | func test1() { 17 | go say("bbbb") 18 | say("tttt") 19 | time.Sleep(5 * 10000) 20 | } 21 | 22 | func test2() { 23 | a := []string{"a", "b", "c"} 24 | fmt.Println(a) 25 | for _, b := range a { 26 | go func() { 27 | fmt.Println(b) 28 | }() 29 | } 30 | } 31 | 32 | func main() { 33 | test2() 34 | var c chan bool 35 | <-c 36 | } 37 | -------------------------------------------------------------------------------- /goroutine/main1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func main() { 9 | 10 | go test1() 11 | 12 | time.Sleep(10 * time.Second) 13 | fmt.Println("main end") 14 | } 15 | 16 | func test1() { 17 | fmt.Println("test1 start") 18 | go test2() 19 | fmt.Println("test1 end") 20 | } 21 | 22 | func test2() { 23 | fmt.Println("test2 start") 24 | time.Sleep(5 * time.Second) 25 | fmt.Println("test2 end") 26 | } 27 | -------------------------------------------------------------------------------- /goroutine/main2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func main() { 9 | timer := time.NewTicker(10 * time.Second) 10 | for { 11 | select { 12 | case <-timer.C: 13 | fmt.Println("timer begin") 14 | go test2() 15 | fmt.Println("timer end") 16 | } 17 | } 18 | } 19 | 20 | func test2() { 21 | fmt.Println("test1 start") 22 | time.Sleep(5 * time.Second) 23 | fmt.Println("test1 end") 24 | } 25 | -------------------------------------------------------------------------------- /goroutine/select.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func dataIn(c chan int, d chan int) { 9 | timer := time.NewTicker(3 * time.Second) 10 | i := 0 11 | for { 12 | select { 13 | case i := <-c: 14 | fmt.Println(i) 15 | // case <-time.After(time.Second * 5): 16 | // fmt.Println(time.Now().String()) 17 | // d <- 10 18 | case <-timer.C: 19 | fmt.Println(time.Now().String()) 20 | i++ 21 | d <- i 22 | } 23 | } 24 | } 25 | 26 | func test() { 27 | c := make(chan int) 28 | d := make(chan int) 29 | go dataIn(c, d) 30 | for { 31 | if j := <-d; j > 10 { 32 | break 33 | } 34 | } 35 | } 36 | 37 | func dataIn1(c, d chan int) { 38 | select { 39 | case <-c: 40 | fmt.Println("cccc") 41 | } 42 | d <- 10 43 | } 44 | 45 | //死锁 46 | func test1() { 47 | c := make(chan int) 48 | d := make(chan int) 49 | go dataIn1(c, d) 50 | <-d 51 | close(c) 52 | 53 | } 54 | 55 | func dataIn3(c chan string, d chan int) { 56 | i := 0 57 | for msg := range c { 58 | fmt.Println(msg) 59 | i++ 60 | d <- i 61 | } 62 | } 63 | 64 | func test3() { 65 | c := make(chan string) 66 | d := make(chan int) 67 | go dataIn3(c, d) 68 | for { 69 | c <- time.Now().String() 70 | if j := <-d; j > 10 { 71 | break 72 | } 73 | } 74 | } 75 | 76 | func main() { 77 | test3() 78 | } 79 | -------------------------------------------------------------------------------- /goroutine/sycn.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/rand" 5 | "fmt" 6 | "sync" 7 | "time" 8 | ) 9 | 10 | type Test struct { 11 | items map[int]string 12 | lock sync.Locker 13 | mutex chan bool 14 | } 15 | 16 | func getRandValue(n int) string { 17 | const alphanum = "0123456789" 18 | var bytes = make([]byte, n) 19 | rand.Read(bytes) 20 | for i, b := range bytes { 21 | bytes[i] = alphanum[b%byte(len(alphanum))] 22 | } 23 | return string(bytes) 24 | } 25 | 26 | func put(t *Test, i int) { 27 | value := getRandValue(5) 28 | t.items[i] = value 29 | } 30 | 31 | func putBylock(t *Test, i int) { 32 | t.lock.Lock() 33 | defer t.lock.Unlock() 34 | value := getRandValue(5) 35 | t.items[i] = value 36 | } 37 | 38 | func putByChan(t *Test, i int) { 39 | t.mutex <- true 40 | value := getRandValue(5) 41 | t.items[i] = value 42 | <-t.mutex 43 | } 44 | 45 | func test2(t *Test) { 46 | for i := 0; i < 10000; i++ { 47 | go putBylock(t, j*10+i) 48 | } 49 | } 50 | 51 | func test1() { 52 | t := &Test{items: make(map[int]string), mutex: make(chan bool, 1)} 53 | 54 | go test2(t) 55 | time.Sleep(5 * time.Second) 56 | fmt.Println(len(t.items)) 57 | for key, value := range t.items { 58 | fmt.Println(key, "-", value) 59 | } 60 | 61 | // a := make(chan bool) 62 | // <-a 63 | } 64 | 65 | func main() { 66 | test1() 67 | } 68 | -------------------------------------------------------------------------------- /heap/cheap.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "container/heap" 5 | "fmt" 6 | ) 7 | 8 | type HeapItem struct { 9 | Key string 10 | Value interface{} 11 | SortValue float64 //排序值 12 | } 13 | 14 | type HeapQueue []*HeapItem 15 | 16 | func (hq HeapQueue) Len() int { 17 | return len(hq) 18 | } 19 | 20 | func (hq HeapQueue) Less(i, j int) bool { 21 | return hq[i].SortValue > hq[j].SortValue 22 | } 23 | 24 | func (hq HeapQueue) Swap(i, j int) { 25 | hq[i], hq[j] = hq[j], hq[i] 26 | } 27 | 28 | func (hq *HeapQueue) Push(x interface{}) { 29 | *hq = append(*hq, x.(*HeapItem)) 30 | } 31 | 32 | func (hq *HeapQueue) Pop() interface{} { 33 | old := *hq 34 | n := len(old) 35 | item := old[n-1] 36 | *hq = old[0 : n-1] 37 | return item 38 | } 39 | 40 | func main() { 41 | hq := &HeapQueue{} 42 | a1:=&HeapItem{Key:"a1",Value:4,SortValue:10} 43 | a2:=&HeapItem{Key:"a2",Value:4,SortValue:2} 44 | a3:=&HeapItem{Key:"a3",Value:4,SortValue:35} 45 | a4:=&HeapItem{Key:"a4",Value:4,SortValue:100} 46 | hq.Push(a1) 47 | hq.Push(a2) 48 | hq.Push(a3) 49 | hq.Push(a4) 50 | heap.Init(hq) 51 | for _,item := range *hq{ 52 | fmt.Println(item.Key) 53 | } 54 | } -------------------------------------------------------------------------------- /heap/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "time" 7 | ) 8 | 9 | var Heap []int 10 | 11 | func parant(i int) int { 12 | return (i - 1) >> 1 13 | } 14 | 15 | func left(i int) int { 16 | return ((i + 1) << 1) - 1 17 | } 18 | func right(i int) int { 19 | return (i + 1) << 1 20 | } 21 | 22 | func swap(i, j int) { 23 | Heap[i], Heap[j] = Heap[j], Heap[i] 24 | } 25 | 26 | func headify(i, size int) { 27 | l := left(i) 28 | r := right(i) 29 | next := i 30 | if l < size && Heap[l]-Heap[i] > 0 { 31 | next = l 32 | } 33 | if r < size && Heap[r]-Heap[next] > 0 { 34 | next = r 35 | } 36 | if i == next { 37 | return 38 | } 39 | swap(i, next) 40 | headify(next, size) 41 | } 42 | 43 | func sort() { 44 | for i := len(Heap) - 1; i > 0; i-- { 45 | swap(0, i) 46 | headify(0, i) 47 | } 48 | } 49 | 50 | func setRoot(value int) { 51 | Heap[0] = value 52 | headify(0, len(Heap)) 53 | } 54 | 55 | func build() { 56 | for i := len(Heap)/2 - 1; i >= 0; i-- { 57 | headify(i, len(Heap)) 58 | } 59 | } 60 | 61 | /** 62 | * 测试堆,取最小的10个元素 63 | */ 64 | func testHead() { 65 | a := make([]int, 0) 66 | for i := 0; i < 10000000; i++ { 67 | a = append(a, rand.Intn(100000000)) 68 | } 69 | b := a[:10] 70 | begin := time.Now().UnixNano() 71 | Heap = a 72 | build() 73 | for i := 10; i < 10000000; i++ { 74 | setRoot(a[i]) 75 | } 76 | sort() 77 | fmt.Println(b) 78 | end := time.Now().UnixNano() 79 | fmt.Println(end - begin) 80 | } 81 | 82 | /** 83 | * 数组排序,冒泡 84 | */ 85 | func sortArray(a []int) { 86 | for i := 0; i < len(a); i++ { 87 | for j := i + 1; j < len(a); j++ { 88 | if a[i] < a[j] { 89 | a[i], a[j] = a[j], a[i] 90 | } 91 | } 92 | } 93 | } 94 | 95 | /** 96 | * 插入新元素 97 | */ 98 | func insertArray(a []int, v int) { 99 | if a[0] < v { 100 | return 101 | } 102 | i := len(a) - 1 103 | for { 104 | if a[i] < v { 105 | i-- 106 | } else { 107 | break 108 | } 109 | } 110 | // 30 20 10 8 5 111 | //移动数组 112 | if i == 0 { 113 | a[0] = v 114 | return 115 | } 116 | 117 | temp := make([]int, len(a)) 118 | copy(temp, a[1:i+1]) 119 | copy(temp[i:], a[i+1:]) 120 | a = temp 121 | } 122 | 123 | /** 124 | * 测试数组,取最小的10个元素 125 | */ 126 | func testArray() { 127 | a := make([]int, 0) 128 | for i := 0; i < 10000000; i++ { 129 | a = append(a, rand.Intn(100000000)) 130 | } 131 | b := a[:10] 132 | begin := time.Now().UnixNano() 133 | sortArray(a) 134 | for i := 10; i < 10000000; i++ { 135 | insertArray(b, a[i]) 136 | } 137 | fmt.Println(b) 138 | end := time.Now().UnixNano() 139 | fmt.Println(end - begin) 140 | } 141 | 142 | func main() { 143 | testHead() 144 | testArray() 145 | } 146 | 147 | /** 148 | * 测试结果 149 | * 100000 150 | * 0.057 151 | * 36.869 152 | * 153 | * 1000000 154 | * 0.900 155 | * ? 156 | * 157 | * 10000000 158 | * 14.492 159 | * ? 160 | */ 161 | -------------------------------------------------------------------------------- /http/httpHelper.go: -------------------------------------------------------------------------------- 1 | package components 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "github.com/astaxie/beego" 8 | "github.com/astaxie/beego/httplib" 9 | "time" 10 | ) 11 | 12 | const ( 13 | CONNECT_TIME_OUT = 100 * time.Second //连接超时时间 14 | READ_WRITE_TIME_OUT = 30 * time.Second //读写超时时间 15 | ) 16 | 17 | // 响应数据结构 18 | type ApiResp struct { 19 | Head ApiHead `json:"head"` 20 | Body interface{} `json:"body,omitempty"` 21 | byteBody []byte 22 | } 23 | 24 | // 响应头结构 25 | type ApiHead struct { 26 | Code int `json:"code"` 27 | Msg string `json:"msg"` 28 | } 29 | 30 | /** 31 | * 获取http请求结果 32 | * url:请求url 33 | * data:body数据对象接口 34 | */ 35 | func GetHttpRequest(url string, data interface{}) (code int, err error) { 36 | begin := time.Now().UnixNano() 37 | beego.Info("Request url:", url) 38 | req := httplib.Get(url) 39 | resp := &ApiResp{} 40 | err = req.ToJson(resp) 41 | if err != nil { 42 | return 43 | } 44 | end := time.Now().UnixNano() 45 | beego.Info("Http response:", resp, ", cost:", end-begin) 46 | 47 | code = resp.Head.Code 48 | if resp.Head.Code != 200 { 49 | err = errors.New(resp.Head.Msg) 50 | return 51 | } 52 | 53 | //获取body数据 54 | err = GetRespBodyData(resp, data) 55 | resp.Body = &data 56 | return 57 | } 58 | 59 | /** 60 | * 获取http请求结果,只支持post 61 | * url:请求地址 62 | * params:post参数 63 | * data:返回数据 64 | */ 65 | func GetPostHttpRequest(url string, params map[string]string, data interface{}) (err error) { 66 | defer func() { 67 | if x := recover(); x != nil { 68 | errStr := fmt.Sprintf("get post fail: params-%v , err-%v", params, x) 69 | err = errors.New(errStr) 70 | } 71 | }() 72 | 73 | begin := time.Now().UnixNano() 74 | req := httplib.Post(url).SetTimeout(CONNECT_TIME_OUT, READ_WRITE_TIME_OUT).Header("Content-Type", "application/x-www-form-urlencoded") 75 | beego.Info("Request url:", url, params) 76 | if params != nil && len(params) > 0 { 77 | for key, value := range params { 78 | req.Param(key, value) 79 | } 80 | } 81 | 82 | resp := &ApiResp{} 83 | err = req.ToJson(resp) 84 | if err != nil { 85 | return 86 | } 87 | end := time.Now().UnixNano() 88 | beego.Info("Http response:", resp, ", cost:", end-begin) 89 | 90 | if resp.Head.Code != 200 { 91 | err = errors.New(resp.Head.Msg) 92 | return 93 | } 94 | 95 | if data != nil { 96 | beego.Debug(resp.Body) 97 | //获取body数据 98 | err = GetRespBodyData(resp, data) 99 | resp.Body = &data 100 | } 101 | 102 | return 103 | } 104 | 105 | /** 106 | * 获取http请求结果,只支持post,返回结构自定义 107 | * url:请求地址 108 | * params:post参数 109 | * data:返回数据 110 | */ 111 | func GetPostHttpRequestData(url string, params map[string]string, respData interface{}) (err error) { 112 | defer func() { 113 | if x := recover(); x != nil { 114 | errStr := fmt.Sprintf("get post fail: params-%v , err-%v", params, x) 115 | err = errors.New(errStr) 116 | } 117 | }() 118 | begin := time.Now().UnixNano() 119 | req := httplib.Post(url).SetTimeout(CONNECT_TIME_OUT, READ_WRITE_TIME_OUT).Header("Content-Type", "application/x-www-form-urlencoded") 120 | beego.Info("Request url:", url, params) 121 | if params != nil && len(params) > 0 { 122 | for key, value := range params { 123 | req.Param(key, value) 124 | } 125 | } 126 | 127 | err = req.ToJson(respData) 128 | if err != nil { 129 | return 130 | } 131 | end := time.Now().UnixNano() 132 | beego.Info("Http response:", respData, ", cost:", end-begin) 133 | 134 | return 135 | } 136 | 137 | func GetRespBodyData(msg *ApiResp, data interface{}) (err error) { 138 | //将body转成bytes 139 | if msg.Body != nil { 140 | //判断body是否为空:body:[]或body:{} 141 | bodyLen := 0 142 | switch msg.Body.(type) { 143 | case map[string]interface{}: 144 | bodyLen = len(msg.Body.(map[string]interface{})) 145 | case []interface{}: 146 | bodyLen = len(msg.Body.([]interface{})) 147 | } 148 | if bodyLen != 0 { 149 | msg.byteBody, _ = json.Marshal(msg.Body) 150 | err = json.Unmarshal(msg.byteBody, data) 151 | } else { 152 | data = nil 153 | err = errors.New("Response body is nil") 154 | } 155 | } 156 | return 157 | } 158 | -------------------------------------------------------------------------------- /http/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "github.com/astaxie/beego/httplib" 8 | ) 9 | 10 | // 响应数据结构 11 | type ApiResp struct { 12 | Head ApiHead `json:"head"` 13 | Body interface{} `json:"body,omitempty"` 14 | byteBody []byte 15 | } 16 | 17 | // 响应头结构 18 | type ApiHead struct { 19 | Code int `json:"code"` 20 | Msg string `json:"msg"` 21 | } 22 | 23 | /** 24 | * 获取http请求结果 25 | * url:请求url 26 | * data:body数据对象接口 27 | */ 28 | func GetHttpRequest(url string, data interface{}) (resp *ApiResp, err error) { 29 | req := httplib.Get(url) 30 | resp = &ApiResp{} 31 | err = req.ToJson(resp) 32 | //获取body数据 33 | err = GetRespBodyData(resp, data) 34 | resp.Body = &data 35 | return 36 | } 37 | 38 | func GetRespBodyData(msg *ApiResp, data interface{}) (err error) { 39 | //将body转成bytes 40 | if msg.Body != nil { 41 | //判断body是否为空:body:[]或body:{} 42 | bodyLen := 0 43 | switch msg.Body.(type) { 44 | case map[string]interface{}: 45 | bodyLen = len(msg.Body.(map[string]interface{})) 46 | case []interface{}: 47 | bodyLen = len(msg.Body.([]interface{})) 48 | } 49 | if bodyLen != 0 { 50 | msg.byteBody, _ = json.Marshal(msg.Body) 51 | err = json.Unmarshal(msg.byteBody, data) 52 | } else { 53 | data = nil 54 | err = errors.New("Response body is nil") 55 | } 56 | } 57 | return 58 | } 59 | 60 | type RoleParm struct { 61 | Name string `json:"LDAP_NAME"` 62 | } 63 | 64 | func test1() { 65 | url := fmt.Sprintf("%s/interface/getEmpsByRoleId.ajax?roleId=%s", "http://ubox-acl.dev.uboxol.com", "11") 66 | roleParms := make([]*RoleParm, 0) 67 | resp, err := GetHttpRequest(url, roleParms) 68 | if err != nil { 69 | fmt.Println(err.Error()) 70 | } 71 | // fmt.Println(roleParms) 72 | result := *resp.Body.(*[]*RoleParm) 73 | fmt.Println(result) 74 | } 75 | 76 | func test2() { 77 | url := "http://m.5read.com/" 78 | req := httplib.Get(url) 79 | b, _ := req.Bytes() 80 | fmt.Println(string(b)) 81 | } 82 | 83 | func test3() { 84 | url := "http://localhost:8081/test" 85 | req := httplib.Post(url) 86 | req.Param("username", "guojing") 87 | req.Param("password", "123456") 88 | b, _ := req.Bytes() 89 | fmt.Println(string(b)) 90 | } 91 | 92 | func main() { 93 | test2() 94 | } 95 | -------------------------------------------------------------------------------- /http/main1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "github.com/astaxie/beego/httplib" 8 | "time" 9 | ) 10 | 11 | const ( 12 | CONNECT_TIME_OUT = 100 * time.Second //连接超时时间 13 | READ_WRITE_TIME_OUT = 30 * time.Second //读写超时时间 14 | ) 15 | 16 | // 响应数据结构 17 | type ApiResp struct { 18 | Head ApiHead `json:"head"` 19 | Body interface{} `json:"body,omitempty"` 20 | byteBody []byte 21 | } 22 | 23 | // 响应头结构 24 | type ApiHead struct { 25 | Code int `json:"code"` 26 | Msg string `json:"msg,omitempty"` 27 | Desc string `json:"desc,,omitempty"` 28 | } 29 | 30 | /** 31 | * 获取http请求结果 32 | * url:请求url 33 | * data:body数据对象接口 34 | */ 35 | func GetHttpRequest(url string, data interface{}) (code int, err error) { 36 | req := httplib.Get(url).SetTimeout(CONNECT_TIME_OUT, READ_WRITE_TIME_OUT) 37 | resp := &ApiResp{} 38 | err = req.ToJson(resp) 39 | if err != nil { 40 | return 41 | } 42 | //获取body数据 43 | err = GetRespBodyData(resp, data) 44 | resp.Body = &data 45 | code = resp.Head.Code 46 | return 47 | } 48 | 49 | /** 50 | * 获取http请求结果,只支持post 51 | * url:请求地址 52 | * params:post参数 53 | * data:返回数据 54 | */ 55 | func GetPostHttpRequest(url string, params map[string]string, data interface{}) (err error) { 56 | req := httplib.Post(url).SetTimeout(CONNECT_TIME_OUT, READ_WRITE_TIME_OUT) 57 | if params != nil && len(params) > 0 { 58 | for key, value := range params { 59 | req.Param(key, value) 60 | } 61 | } 62 | 63 | resp := &ApiResp{} 64 | err = req.ToJson(resp) 65 | if err != nil { 66 | return 67 | } 68 | 69 | //获取body数据 70 | err = GetRespBodyData(resp, data) 71 | resp.Body = &data 72 | return 73 | } 74 | 75 | /** 76 | * 在此对body进行判断,解决body为nil、对象、列表的情况 77 | */ 78 | func GetRespBodyData(msg *ApiResp, data interface{}) (err error) { 79 | //将body转成bytes 80 | if msg.Body != nil { 81 | //判断body是否为空:body:[]或body:{} 82 | bodyLen := 0 83 | switch msg.Body.(type) { 84 | case map[string]interface{}: 85 | bodyLen = len(msg.Body.(map[string]interface{})) 86 | case []interface{}: 87 | bodyLen = len(msg.Body.([]interface{})) 88 | } 89 | if bodyLen != 0 { 90 | msg.byteBody, _ = json.Marshal(msg.Body) 91 | err = json.Unmarshal(msg.byteBody, data) 92 | } else { 93 | data = nil 94 | err = errors.New("Response body is nil") 95 | } 96 | } 97 | return 98 | } 99 | 100 | /** 101 | * 出货量接口数据 102 | */ 103 | type ProSellNum struct { 104 | ProId int64 `json:"proId"` 105 | Num int64 `json:"num"` 106 | } 107 | 108 | type SellResult struct { 109 | VmCode string `json:"vmCode"` 110 | Sn string `json:"sn"` 111 | SellNum []*ProSellNum `json:"sellNum"` 112 | } 113 | 114 | func main() { 115 | defer func() { 116 | if x := recover(); x != nil { 117 | fmt.Println(x) 118 | } 119 | }() 120 | 121 | req := httplib.Post(`http://192.168.8.30:8084/rest/release/soldout/`) 122 | req.Header("Content-type", "text/plain;charset=UTF-8") 123 | data := `{"vmCodes":[{"vmCode":"0001407","sn":"223389047060430848","ctime":"2014-09-08 00:00:01"},{"vmCode":"0001407","sn":"256","ctime":"2014-09-08 00:00:01"}]}` 124 | fmt.Println(data) 125 | req.Param("data", data) 126 | // resp := &ApiResp{} 127 | str, err := req.String() 128 | if err != nil { 129 | fmt.Println(err.Error()) 130 | return 131 | } 132 | fmt.Println(str) 133 | // // err := req.ToJson(resp) 134 | // if err != nil { 135 | // return 136 | // } 137 | 138 | // var sellResults []*SellResult 139 | // //获取body数据 140 | // err = GetRespBodyData(resp, &sellResults) 141 | // fmt.Println(resp.Head, sellResults) 142 | return 143 | } 144 | -------------------------------------------------------------------------------- /iconv/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "fmt" 7 | iconv "github.com/djimenez/iconv-go" 8 | "io/ioutil" 9 | ) 10 | 11 | const ( 12 | OUT_ENCODING = "gbk" //输出编码 13 | ) 14 | 15 | func ExportCsv(head []string, data [][]string) (out []byte, err error) { 16 | fmt.Println(len(head), len(data)) 17 | if len(head) == 0 { 18 | err = errors.New("ExportCsv Head is nil") 19 | return 20 | } 21 | 22 | columnCount := len(head) 23 | 24 | dataStr := bytes.NewBufferString("") 25 | //添加头 26 | for index, headElem := range head { 27 | separate := "," 28 | if index == columnCount-1 { 29 | separate = "\n" 30 | } 31 | dataStr.WriteString(headElem + separate) 32 | } 33 | 34 | //添加数据行 35 | for _, dataArray := range data { 36 | if len(dataArray) != columnCount { //数据项数小于列数 37 | err = errors.New("ExportCsv data format is error.") 38 | } 39 | for index, dataElem := range dataArray { 40 | separate := "," 41 | if index == columnCount-1 { 42 | separate = "\n" 43 | } 44 | dataStr.WriteString(dataElem + separate) 45 | } 46 | } 47 | 48 | //处理编码 49 | out = make([]byte, len(dataStr.Bytes())) 50 | iconv.Convert(dataStr.Bytes(), out, "utf-8", OUT_ENCODING) 51 | return 52 | } 53 | 54 | func main() { 55 | a := []string{"姓名", "年龄"} 56 | 57 | data := make([][]string, 0) 58 | b := []string{"郭靖", "21"} 59 | c := []string{"郭靖", "21"} 60 | d := []string{"郭靖", "21"} 61 | data = append(data, b) 62 | data = append(data, c) 63 | data = append(data, d) 64 | 65 | out, _ := ExportCsv(a, data) 66 | 67 | ioutil.WriteFile("test.csv", out, 0644) 68 | } 69 | -------------------------------------------------------------------------------- /inittest/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | var Config map[string]string = make(map[string]string) 8 | 9 | func Say() { 10 | Config["a"] = "b" 11 | Config["c"] = "d" 12 | } 13 | 14 | func init() { 15 | Say() 16 | } 17 | 18 | func main() { 19 | fmt.Println("aa") 20 | } 21 | -------------------------------------------------------------------------------- /inittest/utils/log.go: -------------------------------------------------------------------------------- 1 | package utils 2 | -------------------------------------------------------------------------------- /interface/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type Human struct { 8 | name string 9 | age int 10 | phone string 11 | } 12 | 13 | type Student struct { 14 | Human 15 | school string 16 | loan float32 17 | } 18 | 19 | type Employee struct { 20 | Human 21 | company string 22 | money float32 23 | } 24 | 25 | func (h *Human) say() { 26 | fmt.Println("Human,", h.name) 27 | } 28 | 29 | func (s *Student) say() { 30 | fmt.Println("Student,", s.name) 31 | s.Human.say() 32 | } 33 | 34 | func main() { 35 | var s Student 36 | s.name = "guojing" 37 | s.say() 38 | } 39 | -------------------------------------------------------------------------------- /interface/main1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type Human struct { 8 | name string 9 | age int 10 | phone string 11 | } 12 | 13 | type Student struct { 14 | Human 15 | school string 16 | loan float32 17 | } 18 | 19 | type Employee struct { 20 | Human 21 | company string 22 | money float32 23 | } 24 | 25 | func (h Human) say() { 26 | fmt.Println("Human,", h.name) 27 | } 28 | 29 | func (s Student) study() { 30 | fmt.Println("Student,", s.name, " is studying") 31 | } 32 | 33 | func (e Employee) work() { 34 | fmt.Println("Employee,", e.name, " is working") 35 | } 36 | 37 | type Men interface { 38 | say() 39 | } 40 | 41 | func test1() { 42 | gj := Student{Human{"gj", 25, "13423141241"}, "FAWFAW", 0.00} 43 | lm := Employee{Human{"lm", 25, "14134231231"}, "HERTGR", 5000} 44 | hm := Human{"gj1", 25, "12412312321"} 45 | var i Men 46 | 47 | i = &hm 48 | i.say() 49 | 50 | i = &gj 51 | i.say() 52 | 53 | i = &lm 54 | i.say() 55 | } 56 | 57 | func test2() { 58 | // gj := Student{Human{"gj", 25, "13423141241"}, "FAWFAW", 0.00} 59 | // lm := Employee{Human{"lm", 25, "14134231231"}, "HERTGR", 5000} 60 | // hm := &Human{"gj1", 25, "12412312321"} 61 | 62 | // if value, ok := hm.(Human); ok { 63 | // fmt.Println("Human", value) 64 | // } 65 | 66 | // if _, ok := gj.(Student); ok { 67 | // fmt.Println("Student") 68 | // } 69 | 70 | // if _, ok := lm.(Employee); ok { 71 | // fmt.Println("Employee") 72 | // } 73 | } 74 | 75 | func test3() { 76 | gj := Student{Human{"gj", 25, "13423141241"}, "FAWFAW", 0.00} 77 | lm := Employee{Human{"lm", 25, "14134231231"}, "HERTGR", 5000} 78 | hm := Human{"gj1", 25, "12412312321"} 79 | var i Men 80 | 81 | i = &hm 82 | fmt.Println(i) 83 | 84 | i = &gj 85 | fmt.Println(i) 86 | 87 | i = &lm 88 | fmt.Println(i) 89 | } 90 | 91 | func test4() { 92 | i := make([]interface{}, 1) 93 | i[0] = 10 94 | if _, ok := i[0].(int); ok { 95 | fmt.Println(i) 96 | } 97 | } 98 | func main() { 99 | // test1() 100 | test4() 101 | // test3() 102 | } 103 | -------------------------------------------------------------------------------- /interface/relect-main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | ) 7 | 8 | type Human struct { 9 | name string 10 | age int 11 | phone string 12 | } 13 | 14 | func (h *Human) say() { 15 | fmt.Println("Human,", h.name) 16 | } 17 | 18 | func main() { 19 | hm := Human{"gj", 25, "12412312312"} 20 | t := reflect.TypeOf(hm) 21 | 22 | fmt.Println(t.NumField()) 23 | 24 | v := reflect.ValueOf(hm) 25 | 26 | fmt.Println(v.FieldByName("name")) 27 | } 28 | -------------------------------------------------------------------------------- /log/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/cihub/seelog" 5 | ) 6 | -------------------------------------------------------------------------------- /mail/mail.go: -------------------------------------------------------------------------------- 1 | package components 2 | 3 | import ( 4 | "crypto/tls" 5 | "encoding/base64" 6 | "fmt" 7 | "github.com/astaxie/beego" 8 | "net" 9 | "net/smtp" 10 | "strings" 11 | ) 12 | 13 | /** 14 | * 向指定用户发送邮件 15 | */ 16 | func SendMailToUsers(title, msg, users string) { 17 | passwd, _ := base64.StdEncoding.DecodeString(beego.AppConfig.String("mail.password")) 18 | 19 | auth := smtp.PlainAuth( 20 | "", 21 | beego.AppConfig.String("mail.username"), 22 | string(passwd), 23 | beego.AppConfig.String("mail.host"), 24 | ) 25 | to := strings.Split(users, ";") 26 | 27 | content_type := "Content-Type: text/html" + "; charset=UTF-8" 28 | bmsg := []byte("To: " + users + "\r\nFrom: " + beego.AppConfig.String("mail.username") + "<" + beego.AppConfig.String("mail.username") + ">\r\nSubject: " + title + "\r\n" + content_type + "\r\n\r\n" + msg) 29 | 30 | err := SendMailTLS(beego.AppConfig.String("mail.host")+":"+beego.AppConfig.String("mail.port"), auth, beego.AppConfig.String("mail.username"), to, bmsg) 31 | if err != nil { 32 | fmt.Println("Error:", err.Error()) 33 | } 34 | } 35 | 36 | /** 37 | * 向指定用户发送邮件,用户邮箱在配置文件中配置(mail.receiver),多个使用;分隔 38 | */ 39 | func SendMail(title, msg string) { 40 | passwd, _ := base64.StdEncoding.DecodeString(beego.AppConfig.String("mail.password")) 41 | 42 | auth := smtp.PlainAuth( 43 | "", 44 | beego.AppConfig.String("mail.username"), 45 | string(passwd), 46 | beego.AppConfig.String("mail.host"), 47 | ) 48 | to := strings.Split(beego.AppConfig.String("mail.receiver"), ";") 49 | 50 | content_type := "Content-Type: text/html" + "; charset=UTF-8" 51 | bmsg := []byte("To: " + beego.AppConfig.String("mail.receiver") + "\r\nFrom: " + beego.AppConfig.String("mail.username") + "<" + beego.AppConfig.String("mail.username") + ">\r\nSubject: " + title + "\r\n" + content_type + "\r\n\r\n" + msg) 52 | 53 | err := SendMailTLS(beego.AppConfig.String("mail.host")+":"+beego.AppConfig.String("mail.port"), auth, beego.AppConfig.String("mail.username"), to, bmsg) 54 | if err != nil { 55 | fmt.Println("Error:", err.Error()) 56 | } 57 | } 58 | 59 | func Dial(addr string) (*smtp.Client, error) { 60 | conn, err := tls.Dial("tcp", addr, nil) //smtp包中net.Dial()当使用ssl连接时会卡住 61 | if err != nil { 62 | fmt.Println(err.Error()) 63 | return nil, err 64 | } 65 | host, _, _ := net.SplitHostPort(addr) 66 | return smtp.NewClient(conn, host) 67 | } 68 | 69 | func SendMailTLS(addr string, a smtp.Auth, from string, to []string, msg []byte) error { 70 | c, err := Dial(addr) 71 | if err != nil { 72 | fmt.Println(err.Error()) 73 | return err 74 | } 75 | defer c.Quit() 76 | 77 | if ok, _ := c.Extension("Auth"); ok { 78 | if err = c.Auth(a); err != nil { 79 | fmt.Println(err.Error()) 80 | return err 81 | } 82 | } 83 | 84 | if err = c.Mail(from); err != nil { 85 | fmt.Println(err.Error()) 86 | return err 87 | } 88 | for _, addr := range to { 89 | if err = c.Rcpt(addr); err != nil { 90 | fmt.Println(err.Error()) 91 | return err 92 | } 93 | } 94 | w, err := c.Data() 95 | if err != nil { 96 | fmt.Println(err.Error()) 97 | return err 98 | } 99 | _, err = w.Write(msg) 100 | if err != nil { 101 | fmt.Println(err.Error()) 102 | return err 103 | } 104 | err = w.Close() 105 | if err != nil { 106 | return err 107 | } 108 | return nil 109 | } 110 | -------------------------------------------------------------------------------- /net/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | ) 8 | 9 | func sayhelloName(w http.ResponseWriter, r *http.Request) { 10 | w.Write("aaaaaaa") 11 | } 12 | 13 | func main() { 14 | http.HandleFunc("/", sayhelloName) //设置访问的路由 15 | err := http.ListenAndServe(":9090", nil) //设置监听的端口 16 | if err != nil { 17 | log.Fatal("ListenAndServe: ", err) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /plugin/select.sub: -------------------------------------------------------------------------------- 1 | import sublime, sublime_plugin 2 | 3 | class TestShowCommand(sublime_plugin.TextCommand): 4 | def run(self, edit): 5 | braces = False 6 | sels = self.view.sel() 7 | for sel in sels: 8 | # sublime.message_dialog(self.view.substr(sel)) 9 | selstr = self.view.substr(sel) 10 | if selstr.find("{")!=-1: 11 | braces=True 12 | if not braces: 13 | new_sels = [] 14 | for sel in sels: 15 | sublime.message_dialog(str(sel.end())) 16 | new_sels.append(self.view.find('\{', sel.end())) 17 | sels.clear() 18 | for sel in new_sels: 19 | sels.add(sel) 20 | self.view.run_command("expand_selection", {"to": "brackets"}) 21 | 22 | -------------------------------------------------------------------------------- /rand/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/rand" 5 | "fmt" 6 | "github.com/Pallinder/go-randomdata" 7 | "math/big" 8 | "strconv" 9 | // "time" 10 | ) 11 | 12 | func test1() { 13 | // ra := math.rand.New(math.rand.NewSource(time.Now().UnixNano())) 14 | // var a string 15 | // for i := 0; i < 5; i++ { 16 | // a = a + strconv.Itoa(ra.Intn(10)) 17 | // } 18 | 19 | var a string 20 | for i := 0; i < 5; i++ { 21 | value, _ := rand.Int(rand.Reader, big.NewInt(10)) 22 | a = a + strconv.Itoa(int(value.Int64())) 23 | } 24 | fmt.Println(a) 25 | } 26 | 27 | func test2() { 28 | fmt.Println(randomdata.Number(10000, 99999)) 29 | } 30 | 31 | func test3(n int) string { 32 | // const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 33 | const alphanum = "0123456789" 34 | var bytes = make([]byte, n) 35 | rand.Read(bytes) 36 | for i, b := range bytes { 37 | bytes[i] = alphanum[b%byte(len(alphanum))] 38 | } 39 | return string(bytes) 40 | } 41 | 42 | func main() { 43 | fmt.Println(test3(5)) 44 | } 45 | -------------------------------------------------------------------------------- /router/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type BaseHandler interface { 8 | execute(msg string) (int, string) 9 | } 10 | 11 | type MyHandler struct { 12 | } 13 | 14 | func (b *MyHandler) execute(msg string) (int, string) { 15 | fmt.Println("My:" + msg) 16 | return 1, "aaa" 17 | } 18 | 19 | type OtherHandler struct { 20 | } 21 | 22 | func (b *OtherHandler) execute(msg string) (int, string) { 23 | fmt.Println("Other:" + msg) 24 | return 2, "bbb" 25 | } 26 | 27 | func main() { 28 | handlers := make(map[string]BaseHandler) 29 | handlers["MyHandler"] = &MyHandler{} 30 | handlers["OtherHandler"] = &OtherHandler{} 31 | 32 | handlerName := "OtherHandler" 33 | 34 | var base BaseHandler 35 | base = handlers[handlerName] 36 | a, _ := base.execute("test") 37 | fmt.Println(a) 38 | 39 | } 40 | -------------------------------------------------------------------------------- /rpc/htttprpc.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "net/http" 7 | "net/rpc" 8 | ) 9 | 10 | type Args struct { 11 | A int 12 | B int 13 | } 14 | 15 | type Quotient struct { 16 | Quo int 17 | Rem int 18 | } 19 | 20 | type Arith int 21 | 22 | func (a *Arith) Mulriply(args *Args, reply *int) error { 23 | *reply = args.A * args.B 24 | return nil 25 | } 26 | 27 | func (a *Arith) Divide(args *Args, quo *Quotient) error { 28 | if a { 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /sign/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "crypto/sha1" 6 | "fmt" 7 | "net/url" 8 | "sort" 9 | "strings" 10 | ) 11 | 12 | /** 13 | * 校验签名,对拼装字符串进行sha1计算 14 | */ 15 | func CheckSign(kwargs map[string]string, priviteKey string) (asign string, ok bool) { 16 | if sign, ok := kwargs["sign"]; ok { 17 | //拼装字符串 18 | msg := GenerateMsg(kwargs, priviteKey) 19 | fmt.Println(msg) 20 | //做sha1处理,取出16进制全小写字符串 21 | h := sha1.New() 22 | h.Write([]byte(msg)) 23 | bs := h.Sum(nil) 24 | mySign := fmt.Sprintf("%x", bs) 25 | asign = mySign 26 | if sign == mySign { 27 | ok = true 28 | } 29 | } 30 | return 31 | } 32 | 33 | /** 34 | * 功能:将安全校验码和参数排序 35 | * 签名原始串按以下方式组装成字符串: 36 | * 1、除sign字段外,所有参数按照字段名的ascii码从小到大排序后使用格式(即key1=value1key2=value2…) 37 | * 拼接而成,空值不传递,不参与签名组串。 38 | * 2、签名原始串中,字段名和字段值都进行URL Encode。 39 | * 3、sign = sign + '_' + priviteKey 40 | */ 41 | func GenerateMsg(kwargs map[string]string, priviteKey string) string { 42 | if kwargs == nil || priviteKey == "" { 43 | return "" 44 | } 45 | var buf bytes.Buffer 46 | keys := make([]string, 0, len(kwargs)) 47 | for k := range kwargs { 48 | keys = append(keys, k) 49 | } 50 | sort.Strings(keys) //按key ascii 顺序排序 51 | for _, k := range keys { 52 | v := kwargs[k] 53 | if strings.ToLower(strings.TrimSpace(k)) == "sign" || strings.TrimSpace(v) == "" { 54 | continue 55 | } 56 | //if buf.Len() > 0 { 57 | // buf.WriteByte('&') 58 | //} 59 | buf.WriteString(url.QueryEscape(k) + "=") 60 | buf.WriteString(url.QueryEscape(v)) 61 | } 62 | return buf.String() + "_" + priviteKey 63 | } 64 | 65 | func main() { 66 | kwargs := make(map[string]string, 0) 67 | kwargs["uid"] = "1000" 68 | kwargs["cts"] = "1234323" 69 | kwargs["sign"] = "aaa" 70 | sign, _ := CheckSign(kwargs, "we7H_E8Xbf_ZH7kT6PQxtsFsIxl-wbVXk4hsw9kRrbo=") 71 | fmt.Println(sign) 72 | } 73 | -------------------------------------------------------------------------------- /sms/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "github.com/astaxie/beego/httplib" 7 | "strings" 8 | "time" 9 | ) 10 | 11 | //curl -d 'phone=15501000792&msg=预定测试&caller=predetermine&night=1"a=1' http://sms.uboxol.com/send_sms 12 | 13 | const ( 14 | CONNECT_TIME_OUT = 10 * time.Second //连接超时时间 15 | READ_WRITE_TIME_OUT = 10 * time.Second //读写超时时间 16 | ) 17 | 18 | var ( 19 | SmsUrl string 20 | PushUrl string 21 | WxUrl string 22 | ) 23 | 24 | // 响应数据结构 25 | type ApiResp struct { 26 | Head ApiHead `json:"head"` 27 | Body interface{} `json:"body,omitempty"` 28 | byteBody []byte 29 | } 30 | 31 | // 响应头结构 32 | type ApiHead struct { 33 | Code int `json:"code"` 34 | Desc string `json:"desc"` 35 | } 36 | 37 | // 短信响应 38 | type SmsResp struct { 39 | Status string `json:"status"` 40 | Msg string `json:"msg"` 41 | } 42 | 43 | /** 44 | * 短信接口-新 45 | */ 46 | func SendSmsNew(phone, msg string) (err error) { 47 | defer func() { 48 | if x := recover(); x != nil { 49 | errStr := fmt.Sprintf("Send sms fail: phone-%s, msg-%s, err-%v", phone, msg, x) 50 | err = errors.New(errStr) 51 | } 52 | }() 53 | 54 | phone = strings.TrimSpace(phone) 55 | msg = strings.TrimSpace(msg) 56 | if phone == "" || msg == "" { 57 | return errors.New("无效参数") 58 | } 59 | 60 | req := httplib.Post("http://sms.uboxol.com/send_sms").SetTimeout(CONNECT_TIME_OUT, READ_WRITE_TIME_OUT).Header("Content-Type", "application/x-www-form-urlencoded") 61 | req.Param("phone", phone) 62 | req.Param("msg", msg) 63 | req.Param("caller", "predetermine") 64 | 65 | resp := &SmsResp{} 66 | err = req.ToJson(resp) 67 | 68 | fmt.Println(resp, err.Error()) 69 | return nil 70 | } 71 | 72 | func main() { 73 | SendSmsNew("15501000792", "预定测试") 74 | return 75 | } 76 | -------------------------------------------------------------------------------- /socket/client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "net" 7 | "os" 8 | ) 9 | 10 | func main() { 11 | service := "127.0.0.1:8899" 12 | fmt.Printf(string(service)) 13 | tcpAddr, err := net.ResolveTCPAddr("tcp4", service) 14 | checkError(err) 15 | conn, err := net.DialTCP("tcp", nil, tcpAddr) 16 | checkError(err) 17 | defer conn.Close() 18 | 19 | _, err = conn.Write([]byte("timestamp")) 20 | checkError(err) 21 | 22 | result, err := ioutil.ReadAll(conn) 23 | checkError(err) 24 | fmt.Println(string(result)) 25 | } 26 | func checkError(err error) { 27 | if err != nil { 28 | fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error()) 29 | os.Exit(1) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /socket/server-long.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | "os" 7 | "time" 8 | ) 9 | 10 | func main() { 11 | service := ":8899" 12 | tcpAddr, err := net.ResolveTCPAddr("tcp4", service) 13 | checkError(err) 14 | 15 | listener, err := net.ListenTCP("tcp", tcpAddr) 16 | checkError(err) 17 | 18 | for { 19 | conn, err := listener.Accept() 20 | if err != nil { 21 | fmt.Fprintf(os.Stderr, "Error: %s", err) 22 | continue 23 | } 24 | fmt.Printf("new connect:", conn.RemoteAddr().String()) 25 | go handleCient(conn) 26 | } 27 | } 28 | 29 | func handleCient(conn net.Conn) { 30 | conn.SetDeadline(time.Now().Add(2 * time.Minute)) 31 | request := make([]byte, 128) 32 | defer conn.Close() 33 | 34 | for { 35 | read_len, err := conn.Read(request) 36 | 37 | if err != nil { 38 | fmt.Fprintf(os.Stderr, "error: %s", err) 39 | break 40 | } 41 | 42 | fmt.Printf(string(read_len)) 43 | 44 | // if read_len == 0 { 45 | // break 46 | // } else if string(request) == "timestamp" { 47 | daytime := time.Now().String() 48 | conn.Write([]byte(daytime)) 49 | // } 50 | } 51 | 52 | request = make([]byte, 128) 53 | } 54 | 55 | func checkError(err error) { 56 | if err != nil { 57 | fmt.Fprintf(os.Stderr, "Fatal error: %s", err) 58 | os.Exit(1) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /socket/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | "os" 7 | "time" 8 | ) 9 | 10 | func main() { 11 | service := ":8899" 12 | tcpAddr, err := net.ResolveTCPAddr("tcp4", service) 13 | checkError(err) 14 | 15 | listener, err := net.ListenTCP("tcp", tcpAddr) 16 | checkError(err) 17 | 18 | for { 19 | conn, err := listener.Accept() 20 | if err != nil { 21 | fmt.Fprintf(os.Stderr, "Error: %s", err) 22 | continue 23 | } 24 | go handleCient(conn) 25 | } 26 | } 27 | 28 | func handleCient(conn net.Conn) { 29 | defer conn.Close() 30 | 31 | daytime := time.Now().String() 32 | conn.Write([]byte(daytime)) 33 | } 34 | 35 | func checkError(err error) { 36 | if err != nil { 37 | fmt.Fprintf(os.Stderr, "Fatal error: %s", err) 38 | os.Exit(1) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /socket/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "go-learn/socket/server/session" 5 | ) 6 | 7 | func main() { 8 | session.Listen("127.0.0.1:8778") 9 | } 10 | -------------------------------------------------------------------------------- /socket/server/session/server.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | ) 7 | 8 | var connMap map[int]*IoSession 9 | 10 | func Listen(connString string) (err error) { 11 | connMap = make(map[int]*IoSession) 12 | ln, err := net.Listen("tcp", connString) 13 | if err != nil { 14 | fmt.Errorf("Error listen to %s", connString) 15 | return err 16 | } 17 | fmt.Println("Server started, listen on %s \n", connString) 18 | for { 19 | conn, err := ln.Accept() 20 | if err != nil { 21 | fmt.Errorf("Error accept conn: %s", err.Error()) 22 | continue 23 | } else { 24 | fmt.Println("Accept: %s", conn.RemoteAddr().String()) 25 | } 26 | session := NewSession(conn) 27 | go Dispatcher(session) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /socket/server/session/session.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "github.com/tyrchen/goutil/uniq" 7 | "net" 8 | ) 9 | 10 | type Message chan []byte 11 | 12 | type IoSession struct { 13 | Id int64 14 | Conn net.Conn 15 | In Message 16 | Out Message 17 | reader *bufio.Reader 18 | writer *bufio.Writer 19 | Quit chan bool 20 | Ready chan string 21 | closed bool 22 | mutx chan bool 23 | ClientIp string 24 | Attrs map[string]interface{} 25 | } 26 | 27 | func NewSession(conn net.Conn) *IoSession { 28 | reader := bufio.NewReader(conn) 29 | writer := bufio.NewWriter(conn) 30 | 31 | session := &IoSession{ 32 | Id: int64(uniq.GetUniq()), 33 | Conn: conn, 34 | In: make(Message), 35 | Out: make(Message), 36 | Quit: make(chan bool), 37 | Ready: make(chan string), 38 | reader: reader, 39 | writer: writer, 40 | closed: false, 41 | mutx: make(chan bool, 1), 42 | ClientIp: conn.RemoteAddr().String(), 43 | Attrs: make(map[string]interface{}, 0), 44 | } 45 | return session 46 | } 47 | 48 | func Dispatcher(session *IoSession) { 49 | fmt.Println("Session Dispatcher", session.Id) 50 | } 51 | -------------------------------------------------------------------------------- /sort/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func quicksort(a []int) { 8 | i := 0 9 | j := len(a) - 1 10 | if i >= j { 11 | return 12 | } 13 | 14 | temp := a[0] 15 | for { 16 | if temp <= a[j] { 17 | j-- 18 | }else{ 19 | a[i] = a[j] 20 | a[j] = temp 21 | } 22 | } 23 | } 24 | 25 | 26 | 4 7 10 1 23 6 27 | 1 7 10 4 23 6 28 | 1 4 10 7 23 6 29 | 30 | 31 | 1 4 6 7 23 10 32 | 1 4 6 7 10 23 -------------------------------------------------------------------------------- /sort/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | /** 8 | * 计算平均值 9 | */ 10 | func CalculateAvg(list []float64) (avgValue float64) { 11 | //处理位数 12 | defer func() { 13 | avgStr := strconv.FormatFloat(avgValue, 'f', 6, 64) 14 | avgValue, _ = strconv.ParseFloat(avgStr, 64) 15 | }() 16 | 17 | if len(list) == 2 { //2个直接计算 18 | return (list[0] + list[1]) / 2 19 | } 20 | listSort(list) 21 | fmt.Println(list) 22 | n := len(list) 23 | 24 | //计算中间60%的区件值 25 | diff := list[n-1] - list[0] 26 | begin := list[0] + diff*0.2 27 | end := list[n-1] - diff*0.2 28 | // fmt.Println(diff * 0.2) 29 | // fmt.Println(begin) 30 | // fmt.Println(end) 31 | 32 | var pIndex, hIndex int 33 | for i := 1; i < n; i++ { 34 | if list[i] >= begin { 35 | pIndex = i 36 | break 37 | } 38 | } 39 | for i := n - 2; i > 0; i-- { 40 | if list[i] <= end { 41 | hIndex = i 42 | break 43 | } 44 | } 45 | if hIndex-pIndex >= 0 { //区间内有值 46 | if hIndex-pIndex == 0 { //直接返回 47 | avgValue = list[hIndex] 48 | return 49 | } 50 | 51 | temp := list[pIndex : hIndex+1] 52 | var sum float64 53 | for i := 0; i < len(temp); i++ { 54 | sum += temp[i] 55 | } 56 | avgValue = sum / float64(len(temp)) 57 | return 58 | } 59 | 60 | //若该区间内无值,则去首位计算平均值 61 | temp := list[1 : n-1] 62 | var sum float64 63 | for i := 0; i < len(temp); i++ { 64 | sum += temp[i] 65 | } 66 | avgValue = sum / float64(len(temp)) 67 | return 68 | } 69 | 70 | /** 71 | * 数组排序,暂用冒泡 72 | */ 73 | func listSort(a []float64) { 74 | for i := 0; i < len(a); i++ { 75 | for j := i + 1; j < len(a); j++ { 76 | if a[i] > a[j] { 77 | a[i], a[j] = a[j], a[i] 78 | } 79 | } 80 | } 81 | } 82 | 83 | func main() { 84 | a := []float64{116.480604, 116.481032, 116.480623, 116.480581, 116.481066, 116.481131, 116.480604} 85 | fmt.Println(CalculateAvg(a)) 86 | } 87 | -------------------------------------------------------------------------------- /srclearn/test1.6: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NotBadPad/go-learn/2866261cfa181c2b33815d46de3da948f2d06daa/srclearn/test1.6 -------------------------------------------------------------------------------- /srclearn/test1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type I interface { 4 | DoSomeWork() 5 | } 6 | 7 | type T struct { 8 | a int 9 | } 10 | 11 | func (t *T) DoSomeWork() { 12 | } 13 | 14 | func main() { 15 | t := &T{} 16 | i := I(t) 17 | print(i) 18 | } 19 | 20 | /** 21 | go tool 6g -W ./test1.go 22 | 23 | 24 | before (*T).DoSomeWork 25 | after walk (*T).DoSomeWork 26 | 27 | before main 28 | . DCL l(15) 29 | . . NAME-main.t u(1) a(1) g(1) l(15) x(0+0) class(PAUTO) f(1) ld(1) tc(1) used(1) PTR64-*main.T 30 | 31 | . AS l(15) colas(1) tc(1) 32 | . . NAME-main.t u(1) a(1) g(1) l(15) x(0+0) class(PAUTO) f(1) ld(1) tc(1) used(1) PTR64-*main.T 33 | . . PTRLIT l(15) esc(no) ld(1) tc(1) PTR64-*main.T 34 | . . . STRUCTLIT l(15) tc(1) main.T 35 | . . . . TYPE l(15) tc(1) implicit(1) type=PTR64-*main.T PTR64-*main.T 36 | 37 | . DCL l(16) 38 | . . NAME-main.i u(1) a(1) g(2) l(16) x(0+0) class(PAUTO) f(1) ld(1) tc(1) used(1) main.I 39 | 40 | . AS l(16) tc(1) 41 | . . NAME-main.autotmp_0000 u(1) a(1) l(16) x(0+0) class(PAUTO) esc(N) tc(1) used(1) PTR64-*main.T 42 | . . NAME-main.t u(1) a(1) g(1) l(15) x(0+0) class(PAUTO) f(1) ld(1) tc(1) used(1) PTR64-*main.T 43 | 44 | . AS l(16) colas(1) tc(1) 45 | . . NAME-main.i u(1) a(1) g(2) l(16) x(0+0) class(PAUTO) f(1) ld(1) tc(1) used(1) main.I 46 | . . CONVIFACE l(16) tc(1) main.I 47 | . . . NAME-main.autotmp_0000 u(1) a(1) l(16) x(0+0) class(PAUTO) esc(N) tc(1) used(1) PTR64-*main.T 48 | 49 | . VARKILL l(16) tc(1) 50 | . . NAME-main.autotmp_0000 u(1) a(1) l(16) x(0+0) class(PAUTO) esc(N) tc(1) used(1) PTR64-*main.T 51 | 52 | . PRINT l(17) tc(1) 53 | . PRINT-list 54 | . . NAME-main.i u(1) a(1) g(2) l(16) x(0+0) class(PAUTO) f(1) ld(1) tc(1) used(1) main.I 55 | after walk main 56 | . DCL l(15) 57 | . . NAME-main.t u(1) a(1) g(1) l(15) x(0+0) class(PAUTO) f(1) ld(1) tc(1) used(1) PTR64-*main.T 58 | 59 | . AS-init 60 | . . AS l(15) tc(1) 61 | . . . NAME-main.autotmp_0002 u(1) a(1) l(15) x(0+0) class(PAUTO) esc(N) tc(1) used(1) main.T 62 | 63 | . . AS l(15) tc(1) 64 | . . . NAME-main.autotmp_0001 u(1) a(1) l(15) x(0+0) class(PAUTO) esc(N) tc(1) used(1) PTR64-*main.T 65 | . . . ADDR u(2) l(15) tc(1) PTR64-*main.T 66 | . . . . NAME-main.autotmp_0002 u(1) a(1) l(15) x(0+0) class(PAUTO) esc(N) tc(1) used(1) main.T 67 | 68 | . . AS u(2) l(15) tc(1) 69 | . . . IND u(2) l(15) tc(1) main.T 70 | . . . . NAME-main.autotmp_0001 u(1) a(1) l(15) x(0+0) class(PAUTO) esc(N) tc(1) used(1) PTR64-*main.T 71 | . AS u(100) l(15) tc(1) 72 | . . NAME-main.t u(1) a(1) g(1) l(15) x(0+0) class(PAUTO) f(1) ld(1) tc(1) used(1) PTR64-*main.T 73 | . . NAME-main.autotmp_0001 u(1) a(1) l(15) x(0+0) class(PAUTO) esc(N) tc(1) used(1) PTR64-*main.T 74 | 75 | . DCL l(16) 76 | . . NAME-main.i u(1) a(1) g(2) l(16) x(0+0) class(PAUTO) f(1) ld(1) tc(1) used(1) main.I 77 | 78 | . AS u(2) l(16) tc(1) 79 | . . NAME-main.autotmp_0000 u(1) a(1) l(16) x(0+0) class(PAUTO) esc(N) tc(1) used(1) PTR64-*main.T 80 | . . NAME-main.t u(1) a(1) g(1) l(15) x(0+0) class(PAUTO) f(1) ld(1) tc(1) used(1) PTR64-*main.T 81 | 82 | . AS-init 83 | . . AS l(16) tc(1) 84 | . . . NAME-main.autotmp_0003 u(1) a(1) l(16) x(0+0) class(PAUTO) esc(N) tc(1) used(1) PTR64-*uint8 85 | . . . NAME-go.itab.*"".T."".I u(1) a(1) l(16) x(0+0) class(PEXTERN) tc(1) used(1) PTR64-*uint8 86 | 87 | . . IF l(16) tc(1) 88 | . . IF-test 89 | . . . EQ l(16) tc(1) bool 90 | . . . . NAME-main.autotmp_0003 u(1) a(1) l(16) x(0+0) class(PAUTO) esc(N) tc(1) used(1) PTR64-*uint8 91 | . . . . LITERAL-nil u(1) a(1) l(16) tc(1) PTR64-*uint8 92 | . . IF-body 93 | . . . AS l(16) tc(1) 94 | . . . . NAME-main.autotmp_0003 u(1) a(1) l(16) x(0+0) class(PAUTO) esc(N) tc(1) used(1) PTR64-*uint8 95 | . . . . CALLFUNC u(100) l(16) tc(1) PTR64-*byte 96 | . . . . . NAME-runtime.typ2Itab u(1) a(1) l(2) x(0+0) class(PFUNC) tc(1) used(1) FUNC-funcSTRUCT-(FIELD- 97 | . . . . . . NAME-runtime.typ·2 u(1) a(1) l(2) x(0+0) class(PPARAM) f(1) PTR64-*byte PTR64-*byte, FIELD- 98 | . . . . . . NAME-runtime.typ2·3 u(1) a(1) l(2) x(8+0) class(PPARAM) f(1) PTR64-*byte PTR64-*byte, FIELD- 99 | . . . . . . NAME-runtime.cache·4 u(1) a(1) l(2) x(16+0) class(PPARAM) f(1) PTR64-*PTR64-*byte PTR64-*PTR64-*byte) PTR64-*byte 100 | . . . . CALLFUNC-list 101 | . . . . . AS u(2) l(16) tc(1) 102 | . . . . . . INDREG-SP a(1) l(16) x(0+0) tc(1) runtime.typ·2 G0 PTR64-*byte 103 | . . . . . . ADDR u(2) a(1) l(16) tc(1) PTR64-*uint8 104 | . . . . . . . NAME-type.*"".T u(1) a(1) l(11) x(0+0) class(PEXTERN) tc(1) uint8 105 | 106 | . . . . . AS u(2) l(16) tc(1) 107 | . . . . . . INDREG-SP a(1) l(16) x(8+0) tc(1) runtime.typ2·3 G0 PTR64-*byte 108 | . . . . . . ADDR u(2) a(1) l(16) tc(1) PTR64-*uint8 109 | . . . . . . . NAME-type."".I u(1) a(1) l(16) x(0+0) class(PEXTERN) tc(1) uint8 110 | 111 | . . . . . AS u(2) l(16) tc(1) 112 | . . . . . . INDREG-SP a(1) l(16) x(16+0) tc(1) runtime.cache·4 G0 PTR64-*PTR64-*byte 113 | . . . . . . ADDR u(2) a(1) l(16) tc(1) PTR64-*PTR64-*uint8 114 | . . . . . . . NAME-go.itab.*"".T."".I u(1) a(1) l(16) x(0+0) class(PEXTERN) tc(1) used(1) PTR64-*uint8 115 | . AS u(100) l(16) tc(1) 116 | . . NAME-main.i u(1) a(1) g(2) l(16) x(0+0) class(PAUTO) f(1) ld(1) tc(1) used(1) main.I 117 | . . EFACE u(2) l(16) tc(1) main.I 118 | . . . NAME-main.autotmp_0003 u(1) a(1) l(16) x(0+0) class(PAUTO) esc(N) tc(1) used(1) PTR64-*uint8 119 | . . . NAME-main.autotmp_0000 u(1) a(1) l(16) x(0+0) class(PAUTO) esc(N) tc(1) used(1) PTR64-*main.T 120 | 121 | . VARKILL l(16) tc(1) 122 | . . NAME-main.autotmp_0000 u(1) a(1) l(16) x(0+0) class(PAUTO) esc(N) tc(1) used(1) PTR64-*main.T 123 | 124 | . EMPTY-init 125 | . . CALLFUNC u(100) l(17) tc(1) 126 | . . . NAME-runtime.printiface u(1) a(1) l(2) x(0+0) class(PFUNC) tc(1) used(1) FUNC-funcSTRUCT-(FIELD-main.I) 127 | . . CALLFUNC-list 128 | . . . AS u(1) l(17) tc(1) 129 | . . . . INDREG-SP a(1) l(17) x(0+0) tc(1) main.I 130 | . . . . NAME-main.i u(1) a(1) g(2) l(16) x(0+0) class(PAUTO) f(1) ld(1) tc(1) used(1) main.I 131 | . EMPTY u(100) l(17) tc(1) 132 | 133 | before init 134 | . IF l(18) tc(1) 135 | . IF-test 136 | . . NE l(18) tc(1) bool 137 | . . . NAME-main.initdone· u(1) a(1) l(18) x(0+0) class(PEXTERN) tc(1) used(1) uint8 138 | . . . LITERAL-0 u(1) a(1) l(18) tc(1) uint8 139 | . IF-body 140 | . . IF l(18) tc(1) 141 | . . IF-test 142 | . . . EQ l(18) tc(1) bool 143 | . . . . NAME-main.initdone· u(1) a(1) l(18) x(0+0) class(PEXTERN) tc(1) used(1) uint8 144 | . . . . LITERAL-2 u(1) a(1) l(18) tc(1) uint8 145 | . . IF-body 146 | . . . RETURN l(18) tc(1) 147 | 148 | . . CALLFUNC l(18) tc(1) 149 | . . . NAME-runtime.throwinit u(1) a(1) l(2) x(0+0) class(PFUNC) tc(1) used(1) FUNC-funcSTRUCT-() 150 | 151 | . AS l(18) tc(1) 152 | . . NAME-main.initdone· u(1) a(1) l(18) x(0+0) class(PEXTERN) tc(1) used(1) uint8 153 | . . LITERAL-1 u(1) a(1) l(18) tc(1) uint8 154 | 155 | . AS l(18) tc(1) 156 | . . NAME-main.initdone· u(1) a(1) l(18) x(0+0) class(PEXTERN) tc(1) used(1) uint8 157 | . . LITERAL-2 u(1) a(1) l(18) tc(1) uint8 158 | 159 | . RETURN l(18) tc(1) 160 | after walk init 161 | . IF l(18) tc(1) 162 | . IF-test 163 | . . NE u(2) l(18) tc(1) bool 164 | . . . NAME-main.initdone· u(1) a(1) l(18) x(0+0) class(PEXTERN) tc(1) used(1) uint8 165 | . . . LITERAL-0 u(1) a(1) l(18) tc(1) uint8 166 | . IF-body 167 | . . IF l(18) tc(1) 168 | . . IF-test 169 | . . . EQ u(2) l(18) tc(1) bool 170 | . . . . NAME-main.initdone· u(1) a(1) l(18) x(0+0) class(PEXTERN) tc(1) used(1) uint8 171 | . . . . LITERAL-2 u(1) a(1) l(18) tc(1) uint8 172 | . . IF-body 173 | . . . RETURN l(18) tc(1) 174 | 175 | . . CALLFUNC u(100) l(18) tc(1) 176 | . . . NAME-runtime.throwinit u(1) a(1) l(2) x(0+0) class(PFUNC) tc(1) used(1) FUNC-funcSTRUCT-() 177 | 178 | . AS u(2) l(18) tc(1) 179 | . . NAME-main.initdone· u(1) a(1) l(18) x(0+0) class(PEXTERN) tc(1) used(1) uint8 180 | . . LITERAL-1 u(1) a(1) l(18) tc(1) uint8 181 | 182 | . AS u(2) l(18) tc(1) 183 | . . NAME-main.initdone· u(1) a(1) l(18) x(0+0) class(PEXTERN) tc(1) used(1) uint8 184 | . . LITERAL-2 u(1) a(1) l(18) tc(1) uint8 185 | 186 | . RETURN l(18) tc(1) 187 | 188 | before I.DoSomeWork 189 | . CALLINTER l(20) tc(1) 190 | . . DOTINTER l(20) x(0+0) tc(1) FUNC-methodSTRUCT-(FIELD-PTR64-*STRUCT-struct {}) funcSTRUCT-() 191 | . . . NAME-main..this u(1) a(1) g(1) l(20) x(0+0) class(PPARAM) f(1) tc(1) used(1) main.I 192 | . . . NAME-main.DoSomeWork u(1) a(1) l(20) x(0+0) 193 | after walk I.DoSomeWork 194 | . CALLINTER u(100) l(20) tc(1) 195 | . . DOTINTER u(2) l(20) x(0+0) tc(1) FUNC-methodSTRUCT-(FIELD-PTR64-*STRUCT-struct {}) funcSTRUCT-() 196 | . . . NAME-main..this u(1) a(1) g(1) l(20) x(0+0) class(PPARAM) f(1) tc(1) used(1) main.I 197 | . . . NAME-main.DoSomeWork u(1) a(1) l(20) x(0+0) 198 | 199 | 200 | 201 | 202 | */ 203 | -------------------------------------------------------------------------------- /textop/Server.json: -------------------------------------------------------------------------------- 1 | {"Servers":[{"ServerName":"ShangHai","ServerIP":"127.0.0.1"},{"ServerName":"BeiJing","ServerIP":"127.0.0.2"}]} -------------------------------------------------------------------------------- /textop/Server.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ShangHai 5 | 127.0.0.1 6 | 7 | 8 | BieJing 9 | 127.0.0.2 10 | 11 | -------------------------------------------------------------------------------- /textop/jsonop.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io/ioutil" 7 | "os" 8 | ) 9 | 10 | type Server struct { 11 | ServerName string 12 | ServerIP string 13 | } 14 | 15 | type Serverslice struct { 16 | Servers []Server 17 | } 18 | 19 | func main() { 20 | /******* 写文件 ******/ 21 | // var s Serverslice 22 | // s.Servers = append(s.Servers, Server{"ShangHai", "127.0.0.1"}) 23 | // s.Servers = append(s.Servers, Server{"BeiJing", "127.0.0.2"}) 24 | 25 | // b, err := json.Marshal(s) 26 | // if err != nil { 27 | // fmt.Println("Server.json read fail:", err) 28 | // return 29 | // } 30 | 31 | // fout, err := os.Create("Server.json") 32 | // defer fout.Close() 33 | // if err != nil { 34 | // fmt.Println("Server.json create fail:", err) 35 | // return 36 | // } 37 | 38 | // fmt.Print(string(b)) 39 | 40 | // fout.Write(b) 41 | 42 | /******* 读文件 ******/ 43 | fin, err := os.Open("Server.json") 44 | 45 | if err != nil { 46 | fmt.Println("Server.json read fail:", err) 47 | return 48 | } 49 | defer fin.Close() 50 | 51 | data, err := ioutil.ReadAll(fin) 52 | if err != nil { 53 | fmt.Println("Server.json read fail:", err) 54 | return 55 | } 56 | 57 | var s Serverslice 58 | json.Unmarshal(data, &s) 59 | fmt.Println(s.Servers[0].ServerName) 60 | } 61 | -------------------------------------------------------------------------------- /textop/jsonop2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | type Msg struct { 9 | Head MsgHead `json:"head"` 10 | Body interface{} `json:"body"` 11 | } 12 | 13 | type MsgHead struct { 14 | Mid string `json:"mid,omitempty"` 15 | Type string `json:"type,omitempty"` 16 | Code int `json:"code,omitempty"` 17 | Desc string `json:"msg,omitempty"` 18 | Cts int64 `json:"cts"` 19 | } 20 | 21 | type StationStatus struct { 22 | printerStatus int64 `json:"printerStatus"` //打印机状态 23 | cameraStatus int64 `json:"cameraStatus"` //摄像头状态 24 | keyboardStatus int64 `json:"keyboardStatus"` //键盘状态 25 | sweepgunStatus int64 `json:"sweepgunStatus"` //扫描头状态 26 | } 27 | 28 | func test1() { 29 | msg := &Msg{} 30 | str := `{"head":{"mid":"c12345678","type":"connect"},"body":{"vmCode":"00001","token":"KYMKYVOKAxLmIvelC7HqVRMKOeyYtikhcS6X7K8CX3M=","cts":1341234223}}` 31 | err := json.Unmarshal([]byte(str), msg) 32 | if err != nil { 33 | fmt.Println(err) 34 | } 35 | 36 | bytes, _ := json.Marshal(msg.Body) 37 | fmt.Println("body:", string(bytes)) 38 | 39 | type Parma struct { 40 | VmCode string `json:"vmCode,omitempty"` 41 | Token string `json:"token,omitempty"` 42 | } 43 | parma := &Parma{} 44 | err = json.Unmarshal(bytes, parma) 45 | if err != nil { 46 | fmt.Println(err) 47 | } 48 | fmt.Println(parma) 49 | } 50 | 51 | func test2() { 52 | msg := &Msg{} 53 | str := `{"head":{"mid":"c12345678","type":"boxStatus"},"body":[{"boxSeq":5,"boxCode":"A5","deviceId":1,"status":1},{"boxSeq":6,"boxCode":"A6","deviceId":1,"status":1}]}` 54 | err := json.Unmarshal([]byte(str), msg) 55 | if err != nil { 56 | fmt.Println(err) 57 | } 58 | 59 | bytes, _ := json.Marshal(msg.Body) 60 | fmt.Println("body:", string(bytes)) 61 | 62 | type Parma struct { 63 | BoxSeq int64 `json:"boxSeq,omitempty"` 64 | BoxCode string `json:"boxCode,omitempty"` 65 | DeviceId int64 `json:"deviceId,omitempty"` 66 | Status int `json:"status,omitempty"` 67 | } 68 | parmas := []*Parma{} 69 | err = json.Unmarshal(bytes, &parmas) 70 | if err != nil { 71 | fmt.Println(err) 72 | } 73 | for _, parma := range parmas { 74 | fmt.Println(parma.BoxCode) 75 | } 76 | } 77 | 78 | func test3() { 79 | stationStatus := &StationStatus{} 80 | str := `{"printerStatus":2,"cameraStatus":2,"keyboardStatus":2,"sweepgunStatus":2}` 81 | err := json.Unmarshal([]byte(str), stationStatus) 82 | if err != nil { 83 | fmt.Println(err) 84 | } 85 | fmt.Println(stationStatus) 86 | } 87 | 88 | func test4() { 89 | msg := &Msg{} 90 | str := `{"head":{"mid":"c12345678","type":"boxStatus","cts":139943085681542411}}` 91 | err := json.Unmarshal([]byte(str), msg) 92 | if err != nil { 93 | fmt.Println(err) 94 | } 95 | fmt.Println(msg.Head.Cts) 96 | } 97 | 98 | func test5() { 99 | msg := &Msg{} 100 | err := json.Unmarshal([]byte(nil), msg) 101 | if err != nil { 102 | fmt.Println(err) 103 | } 104 | fmt.Println(msg.Head.Cts) 105 | } 106 | 107 | func test6() { 108 | msg := &Msg{} 109 | 110 | str := `{"head":{"mid":"c12345678","type":"boxStatus"},"body":[{"boxSeq":5,"boxCode":"A5","deviceId":1,"status":1},{"boxSeq":6,"boxCode":"A6","deviceId":1,"status":1}]}` 111 | 112 | type Parma struct { 113 | BoxSeq int64 `json:"boxSeq,omitempty"` 114 | BoxCode string `json:"boxCode,omitempty"` 115 | DeviceId int64 `json:"deviceId,omitempty"` 116 | Status int `json:"status,omitempty"` 117 | } 118 | 119 | parmas := make([]*Parma, 0) 120 | msg.Body = parmas 121 | err := json.Unmarshal([]byte(str), msg) 122 | if err != nil { 123 | fmt.Println(err) 124 | } 125 | 126 | fmt.Println(msg.Body) 127 | } 128 | 129 | func test7() { 130 | a := map[int]string{3: "aaa", 4: "bbb", 5: "ccc"} 131 | bytes, err := json.Marshal(a) 132 | if err != nil { 133 | fmt.Println(err.Error()) 134 | } 135 | fmt.Println(string(bytes)) 136 | } 137 | 138 | func test8() { 139 | a := make([]interface{}, 2) 140 | b := map[string]interface{}{"aaa": "aaa", "bbb": 12} 141 | a[0] = b 142 | a[1] = b 143 | bytes, err := json.Marshal(a) 144 | if err != nil { 145 | fmt.Println(err.Error()) 146 | } 147 | fmt.Println(string(bytes)) 148 | } 149 | 150 | func test9() { 151 | type Parma struct { 152 | VmCode string `json:"vmCode"` 153 | Sn int64 `json:"sn"` 154 | CTime string `json:"ctime"` 155 | } 156 | 157 | parmas := make([]*Parma, 0) 158 | parma := &Parma{ 159 | VmCode: "0001407", 160 | Sn: 1, 161 | CTime: "2014-09-10 11:25:30", 162 | } 163 | parmas = append(parmas, parma) 164 | parma = &Parma{ 165 | VmCode: "0001407", 166 | Sn: 1, 167 | CTime: "2014-09-10 11:25:30", 168 | } 169 | parmas = append(parmas, parma) 170 | bytes, err := json.Marshal(parmas) 171 | if err != nil { 172 | fmt.Println(err.Error()) 173 | } 174 | fmt.Println(string(bytes)) 175 | 176 | } 177 | 178 | func test10() { 179 | type ProSellNum struct { 180 | ProId int64 `json:"proId"` 181 | Num int64 `json:num` 182 | } 183 | 184 | type SellResult struct { 185 | VmCode string `json:"vmCode"` 186 | Sn int64 `json:"sn"` 187 | SellNum []*ProSellNum `json:"sellNum"` 188 | } 189 | 190 | jsonStr := `[{"vmCode": "0001407", "sn": 2, "sellNum": [{"proId": 54, "num": 100}, {"proId": 12, "num": 100}, {"proId": 33, "num": 100}]},{"vmCode": "0001407", "sn": 2, "sellNum": [{"proId": 54, "num": 100}, {"proId": 12, "num": 100}, {"proId": 33, "num": 100}]},{"vmCode": "0001407", "sn": 2, "sellNum": [{"proId": 54, "num": 100}, {"proId": 12, "num": 100}, {"proId": 33, "num": 100}]}]` 191 | 192 | var srs []*SellResult 193 | err := json.Unmarshal([]byte(jsonStr), &srs) 194 | if err != nil { 195 | fmt.Println(err.Error()) 196 | } else { 197 | fmt.Printf(srs[0].VmCode) 198 | } 199 | 200 | } 201 | 202 | /** 203 | * 出货量接口数据 204 | */ 205 | type ProSellNum struct { 206 | ProId int64 `json:"proId"` 207 | Num int64 `json:"num"` 208 | } 209 | 210 | type SellResult struct { 211 | VmCode string `json:"vmCode"` 212 | Sn int64 `json:"sn"` 213 | SellNum []*ProSellNum `json:"sellNum"` 214 | } 215 | 216 | func main() { 217 | test1() 218 | } 219 | -------------------------------------------------------------------------------- /textop/regexpop.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "net/http" 7 | "regexp" 8 | "strings" 9 | ) 10 | 11 | //判断ip 12 | func IsIP(ip string) (b bool) { 13 | if m, _ := regexp.MatchString("^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$", ip); !m { 14 | return false 15 | } 16 | 17 | return true 18 | } 19 | 20 | func crawlerBaidu() { 21 | resp, err := http.Get("http://www.baidu.com") 22 | if err != nil { 23 | fmt.Println("http get error") 24 | } 25 | defer resp.Body.Close() 26 | body, err := ioutil.ReadAll(resp.Body) 27 | if err != nil { 28 | fmt.Println("http get error") 29 | } 30 | 31 | src := string(body) 32 | fmt.Print(src) 33 | 34 | re, _ := regexp.Compile("\\<[\\S\\s]+?\\>") 35 | src = re.ReplaceAllStringFunc(src, strings.ToLower) 36 | fmt.Print(src) 37 | } 38 | 39 | func test1() { 40 | src := []byte(` 41 | call hello alice 42 | hello bob 43 | call hello eve 44 | `) 45 | pat := regexp.MustCompile(`(?m)(call)\s+(?P\w+)\s+(?P.+)\s*$`) 46 | res := []byte{} 47 | for _, s := range pat.FindAllSubmatchIndex(src, -1) { 48 | res = pat.Expand(res, []byte("$cmd('$arg')\n"), src, s) 49 | } 50 | fmt.Println(string(res)) 51 | } 52 | 53 | func test2() { 54 | src := `123.125.71.118 - - [11/May/2014:00:00:05 +0800] "GET /company/news/24.html HTTP/1.1" 200 3661 "-" "Mozilla/5.0 (iphone; U; CPU iPhone OS 4_3_5 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5" 120.201.105.162, 127.0.0.1, 10.65.43.62 0.004 0.004` 55 | pat := regexp.MustCompile(`^(?P.*?) .*? .*? \[(?P.*?)\] "(?PGET|POST) (?P.*?)" (?P.*?) (?P.*?) .*? ".*?" .* (?P.*?) (?P.*?)\s*$`) 56 | fmt.Printf("%v \n", pat.FindStringSubmatch(src)) 57 | } 58 | 59 | func test3() { 60 | src := `123.125.71.118 - - [11/May/2014:00:00:05 +0800] "GET /company/news/24.html HTTP/1.1" 200 3661 "-" "Mozilla/5.0 (iphone; U; CPU iPhone OS 4_3_5 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5" 120.201.105.162, 127.0.0.1, 10.65.43.62 0.004 0.004` 61 | pat := regexp.MustCompile(`^(?P.*?) .*? .*? \[(?P.*?)\] "(?PGET|POST) (?P.*?) .*?" (?P.*?) (?P.*?) .*? .* (?P.*?) (?P.*?)\s*$`) 62 | values := pat.FindStringSubmatch(src) 63 | values = values[1:] 64 | fmt.Printf("%v \n", values) 65 | } 66 | 67 | func test4() { 68 | src := `abcdefgh` 69 | pat := regexp.MustCompile(`(?Pcd)(?Pef)`) 70 | fmt.Printf("%v \n", pat.FindStringSubmatch(src)) 71 | } 72 | 73 | func test5() { 74 | s := `123.125.71.118 - - [11/May/2014:00:00:05 +0800] "GET /company/news/24.html HTTP/1.1" 200 3661 "-" "Mozilla/5.0 (iphone; U; CPU iPhone OS 4_3_5 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5" 120.201.105.162, 127.0.0.1, 10.65.43.62 0.005 0.004` 75 | //时间 76 | index := strings.Index(s, "[") 77 | index1 := strings.Index(s, "]") 78 | fmt.Println(s[index+1 : index1]) 79 | 80 | //uri 81 | index = strings.Index(s, "\"") 82 | index1 = strings.Index(s[index+1:], "\"") 83 | index2 := index + index1 + 1 84 | temp := s[index+1 : index+index1+1] 85 | index = strings.Index(temp, " ") 86 | index1 = strings.Index(temp[index+1:], " ") 87 | fmt.Println(temp[index+1 : index+index1+1]) 88 | 89 | //状态码 90 | index = strings.Index(s[index2+2:], " ") 91 | fmt.Println(s[index2+2 : index2+2+index]) 92 | //内容长度 93 | index = index2 + 2 + index 94 | index1 = strings.Index(s[index+1:], " ") 95 | fmt.Println(s[index+1 : index1+1+index]) 96 | 97 | //响应时间 98 | index1 = strings.LastIndex(s, " ") 99 | fmt.Println(s[index1+1:]) 100 | index = strings.LastIndex(s[:index1], " ") 101 | fmt.Println(s[index+1 : index1]) 102 | } 103 | func main() { 104 | // fmt.Println(IsIP("127.a.0.1")) 105 | test3() 106 | } 107 | -------------------------------------------------------------------------------- /textop/template.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "html/template" 5 | "os" 6 | ) 7 | 8 | type Person struct { 9 | UserName string 10 | Emails map[string]interface{} 11 | Names []string 12 | } 13 | 14 | func test1() { 15 | // t := template.New("test") 16 | // t, _ = t.Parse(` 17 | // {{.UserName}} 18 | // {{.Emails.v1}} 19 | // `) 20 | // user := Person{"guojing", make(map[string]string, 0), make([]string, 3)} 21 | // user.Emails["v1"] = "test1" 22 | // user.Emails["v2"] = "test2" 23 | // user.Names[0] = "aaaaa" 24 | // t.Execute(os.Stdout, user) 25 | } 26 | 27 | func test2() { 28 | t := template.New("test") 29 | t, _ = t.Parse(` 30 | {{.UserName}} 31 | {{.Emails.v2.b}} 32 | {{range .Emails.v3}} 33 | {{.}} 34 | {{end}} 35 | `) 36 | user := Person{"guojing", make(map[string]interface{}, 0), make([]string, 3)} 37 | user.Emails["v1"] = "test1" 38 | user.Emails["v2"] = map[string]string{"a": "4321", "b": "123"} 39 | user.Emails["v3"] = []int{1, 3, 4, 2, 3} 40 | user.Names[0] = "aaaaa" 41 | t.Execute(os.Stdout, user) 42 | } 43 | 44 | func main() { 45 | test2() 46 | } 47 | -------------------------------------------------------------------------------- /textop/templateHelper.go: -------------------------------------------------------------------------------- 1 | package components 2 | 3 | import ( 4 | "bytes" 5 | "github.com/astaxie/beego" 6 | "html/template" 7 | "time" 8 | ) 9 | 10 | /** 11 | * 获取模板内容,模板默认放在template下 12 | */ 13 | func GetTemplateContent(tempName string, data map[string]interface{}) (content string, err error) { 14 | t := template.New(tempName) 15 | t, err = t.ParseFiles("template/" + tempName) 16 | if err != nil { 17 | beego.Error("Error template :", err.Error()) 18 | } 19 | 20 | buff := bytes.NewBufferString("") 21 | err = t.Execute(buff, data) 22 | if err != nil { 23 | beego.Error("Error template :", err.Error()) 24 | } 25 | content = buff.String() 26 | return 27 | } 28 | 29 | /** 30 | * 转化时间 31 | */ 32 | func ConverUnixToTime(value int64) string { 33 | return time.Unix(value, 0).Format("2006-01-02 15:04:05") 34 | } 35 | 36 | func IsShow(value int64) string { 37 | if value == 0 { 38 | return "" 39 | } 40 | return "show" 41 | } 42 | 43 | func init() { 44 | beego.AddFuncMap("ConverUnixToTime", ConverUnixToTime) 45 | beego.AddFuncMap("IsShow", IsShow) 46 | } 47 | -------------------------------------------------------------------------------- /textop/test.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | username 4 | PGTIOU-84678-8a9d... 5 | 6 | -------------------------------------------------------------------------------- /textop/urlencode.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/url" 6 | "strings" 7 | ) 8 | 9 | func test1() { 10 | var str string = `http://workflow.uboxol.com/download/1441678136510089755_7%E5%8F%B7-%E4%B8%AD%E5%AD%A6%E7%89%88%E7%A7%9F%E8%B5%81%E5%8D%8F%E8%AE%AE%E9%95%BF%E9%83%A1%E5%8F%8C%E8%AF%AD.docx,http://workflow.uboxol.com/download/1441678136510089755_7%E5%8F%B7-%E4%B8%AD%E5%AD%A6%E7%89%88%E7%A7%9F%E8%B5%81%E5%8D%8F%E8%AE%AE%E9%95%BF%E9%83%A1%E5%8F%8C%E8%AF%AD.docx` 11 | strEn, _ := url.QueryUnescape(strings.Replace(str, `http://workflow.uboxol.com/download/`, "", -1)) 12 | fmt.Println(strEn) 13 | 14 | } 15 | 16 | func ConvertAttachs(attachs string) string { 17 | if len(attachs) == 0 { 18 | return "" 19 | } 20 | 21 | if strings.Index(attachs, "/download/") >= 0 { 22 | return attachs 23 | } 24 | 25 | result := "" 26 | atts := strings.Split(attachs, ",") 27 | for _, att := range atts { 28 | result = result + "http://aaaa/download/" + url.QueryEscape(att) + "," 29 | } 30 | 31 | if len(result) > 0 { 32 | result = result[0 : len(result)-1] 33 | } 34 | return result 35 | } 36 | 37 | func main() { 38 | str := `1441678136510089755_7号-中学版租赁协议长郡双语.docx,1441678136510089755_7号-中学版租赁协议长郡双语.docx` 39 | fmt.Println(ConvertAttachs(str)) 40 | } 41 | -------------------------------------------------------------------------------- /textop/xmlop.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/xml" 5 | "fmt" 6 | "io/ioutil" 7 | "os" 8 | ) 9 | 10 | type Servers struct { 11 | XMLName xml.Name `xml:"servers"` 12 | Version string `xml:"version,attr"` 13 | Svs []server `xml:"server"` 14 | Description string `xml:",innerxml"` 15 | } 16 | 17 | type server struct { 18 | ServerName string `xml:"serverName"` 19 | ServerIp string `xml:"serverIP"` 20 | } 21 | 22 | func test1() { 23 | <<<<<<< HEAD 24 | /******* 写文件 ******/ 25 | // v := &Servers{Version: "1"} 26 | // v.Svs = append(v.Svs, server{"ShangHai", "127.0.0.1"}) 27 | // v.Svs = append(v.Svs, server{"BieJing", "127.0.0.2"}) 28 | // output, err := xml.MarshalIndent(v, "\t", "\t") 29 | // if err != nil { 30 | // fmt.Printf("error:%v", err) 31 | // } 32 | 33 | // fout, err := os.Create("Server.xml") 34 | // defer fout.Close() 35 | // if err != nil { 36 | // fmt.Println("Server.xml create fail:", err) 37 | // return 38 | // } 39 | 40 | // fout.Write([]byte(xml.Header)) 41 | // fout.Write(output) 42 | 43 | ======= 44 | >>>>>>> 3a4d65ada1be726a4fc6f76d2dac5aaf2e304328 45 | /******* 读文件 ******/ 46 | 47 | fin, err := os.Open("Server.xml") 48 | 49 | if err != nil { 50 | fmt.Println("Server.xml read fail:", err) 51 | return 52 | } 53 | defer fin.Close() 54 | 55 | data, err := ioutil.ReadAll(fin) 56 | if err != nil { 57 | fmt.Println("Server.xml read fail:", err) 58 | return 59 | } 60 | v := Servers{} 61 | err = xml.Unmarshal(data, &v) 62 | if err != nil { 63 | fmt.Println("Server.xml read fail:", err) 64 | return 65 | } 66 | 67 | fmt.Println(v) 68 | } 69 | 70 | func test2() { 71 | <<<<<<< HEAD 72 | data := ` 73 | 74 | username 75 | PGTIOU-84678-8a9d... 76 | 77 | ` 78 | type AuthenticationSuccess struct { 79 | User string `xml:"user"` 80 | } 81 | type Resp struct { 82 | XMLName xml.Name `xml:"serviceResponse"` 83 | Auth AuthenticationSuccess `xml:"authenticationSuccess"` 84 | } 85 | 86 | value := &Resp{} 87 | err := xml.Unmarshal([]byte(data), &value) 88 | if err != nil { 89 | fmt.Println("Server.xml read fail:", err) 90 | return 91 | } 92 | 93 | fmt.Println(value) 94 | } 95 | 96 | func main() { 97 | test2() 98 | ======= 99 | /******* 写文件 ******/ 100 | // v := &Servers{Version: "1"} 101 | // v.Svs = append(v.Svs, server{"ShangHai", "127.0.0.1"}) 102 | // v.Svs = append(v.Svs, server{"BieJing", "127.0.0.2"}) 103 | // output, err := xml.MarshalIndent(v, "\t", "\t") 104 | // if err != nil { 105 | // fmt.Printf("error:%v", err) 106 | // } 107 | 108 | // fout, err := os.Create("Server.xml") 109 | // defer fout.Close() 110 | // if err != nil { 111 | // fmt.Println("Server.xml create fail:", err) 112 | // return 113 | // } 114 | 115 | // fout.Write([]byte(xml.Header)) 116 | // fout.Write(output) 117 | 118 | } 119 | 120 | func main() { 121 | test1() 122 | >>>>>>> 3a4d65ada1be726a4fc6f76d2dac5aaf2e304328 123 | } 124 | -------------------------------------------------------------------------------- /time/beego-timer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/astaxie/beego/toolbox" 5 | ) 6 | 7 | func main() { 8 | task := toolbox.NewTask("stock_stat", "0 30 7 * * *", StockTaskNew) 9 | toolbox.AddTask("stock_stat", task) 10 | toolbox.StartTask() 11 | } 12 | -------------------------------------------------------------------------------- /time/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | "time" 7 | ) 8 | 9 | func test1() { 10 | // for { 11 | // select { 12 | // case <-time.After(time.Second * 3): 13 | // fmt.Println(time.Now().String()) 14 | // } 15 | // } 16 | } 17 | 18 | func test2() { 19 | st := time.Now().Format("2006-01-02 15:04:05") 20 | fmt.Println(st) 21 | } 22 | 23 | func test3() { 24 | 25 | } 26 | 27 | func test4() { 28 | var a bool = false 29 | timer := time.NewTicker(time.Second * 3) 30 | for { 31 | if a { 32 | break 33 | } 34 | select { 35 | case <-timer.C: 36 | fmt.Println(time.Now()) 37 | } 38 | } 39 | } 40 | 41 | func test5() { 42 | str := "11/May/2014:00:00:05 +0800" 43 | index := strings.Index(str, " ") 44 | str = str[:index] 45 | // strings.Split(str, sep) 46 | fmt.Println(str) 47 | 48 | // t1, _ := time.Parse("11/Jan/2006:15:04:05 -0700", str) 49 | // fmt.Println(t1) 50 | } 51 | 52 | func test6() { 53 | str := "12/May/2014:00:00:05 +0800" 54 | t1, _ := time.Parse("2/Jan/2006:15:04:05 -0700", str) 55 | fmt.Println(t1) 56 | } 57 | 58 | func test7() { 59 | ti := time.Now() 60 | fmt.Println(ti.Format("2006-01-02")) 61 | } 62 | 63 | func test8() { 64 | t := time.Now() 65 | t1 := time.Date(t.Year(), t.Month(), t.Day(), 24, 0, 0, 0, t.Location()) 66 | fmt.Println(t1.Unix() - t.Unix()) 67 | } 68 | 69 | func test9() { 70 | for i := 0; i < 10; i++ { 71 | fmt.Println(time.Now().UnixNano()) 72 | } 73 | } 74 | func test10() { 75 | str := "2014-06-12 16:32:00" 76 | t1, _ := time.Parse("2006-01-02 15:04:05", str) 77 | fmt.Println(t1) 78 | } 79 | 80 | func test11() { 81 | t := time.Now() 82 | t = t.AddDate(0, -1, -1) 83 | fmt.Println(t.String()) 84 | } 85 | 86 | func test12() { 87 | nowDate, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02")) 88 | begin := nowDate.AddDate(0, 0, -1).Format("2006-01-02 15:04:05") 89 | end := nowDate.Format("2006-01-02 15:04:05") 90 | fmt.Println(nowDate.String(), begin, end) 91 | } 92 | 93 | func test13() { 94 | str, _ := time.Parse("20060102150405", "20080102150405") 95 | fmt.Println(str) 96 | } 97 | 98 | func task1() { 99 | timer := time.NewTicker(1 * time.Second) 100 | for { 101 | select { 102 | case <-timer.C: 103 | fmt.Println("aaaa") 104 | } 105 | } 106 | } 107 | 108 | func task2() { 109 | timer := time.NewTicker(1 * time.Second) 110 | for { 111 | select { 112 | case <-timer.C: 113 | fmt.Println("bbbb") 114 | } 115 | } 116 | str := "2014-06-12 16:32:00" 117 | t1, _ := time.Parse("20060102150405", str) 118 | fmt.Println(t1) 119 | } 120 | 121 | func test14() { 122 | t := time.Unix(1414570076, 0) 123 | ts := t.Format("2006-01-02 15:04:05") 124 | fmt.Println(ts) 125 | } 126 | 127 | func test15() { 128 | from := "2014-11-12" 129 | to := "2014-11-15" 130 | 131 | t, _ := time.Parse("2006-01-02", from) 132 | tto, _ := time.Parse("2006-01-02", to) 133 | 134 | for t.Before(tto) { 135 | fmt.Println(t.Format("2006-01-02")) 136 | t = t.AddDate(0, 0, 1) 137 | } 138 | 139 | fmt.Println(tto.Format("2006-01-02")) 140 | } 141 | 142 | func main() { 143 | test15() 144 | } 145 | -------------------------------------------------------------------------------- /time/tasktimer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | type TaskTimer struct { 9 | Interval int64 //执行间隔,单位秒 10 | ExecFunc func() //调度执行方法 11 | ExecTime string //执行时间,格式yyyy-MM-dd hh-mm-ss 12 | wait chan bool //阻塞chan,在start中阻塞,防止主线程结束导致程序结束 13 | IsStop bool //结束标记 14 | } 15 | 16 | /** 17 | * 创建TaskTimer 18 | */ 19 | func CreateTaskTimer(execTime string, interval int64, execFunc func()) *TaskTimer { 20 | t := &TaskTimer{ 21 | Interval: interval, 22 | ExecTime: execTime, 23 | ExecFunc: execFunc, 24 | wait: make(chan bool, 1), 25 | } 26 | return t 27 | } 28 | 29 | /** 30 | * 启动任务 31 | */ 32 | func (t *TaskTimer) Start() { 33 | //计算首次执行时间 34 | tnow := time.Now() 35 | exeTime, _ := time.ParseInLocation("2006-01-02 15:04:05", t.ExecTime, tnow.Location()) 36 | diff := exeTime.Unix() - tnow.Unix() 37 | for diff < 0 { //小于0则加一个间隔时间,直到大于0为止 38 | diff += t.Interval 39 | } 40 | 41 | time.AfterFunc(time.Duration(diff)*time.Second, func() { 42 | if !t.IsStop { 43 | t.ExecFunc() //第一次执行 44 | } else { 45 | return 46 | } 47 | for { 48 | timer := time.NewTimer(time.Duration(t.Interval) * time.Second) //每隔 49 | select { 50 | case <-timer.C: 51 | if !t.IsStop { 52 | t.ExecFunc() 53 | } else { 54 | return 55 | } 56 | } 57 | } 58 | }) 59 | 60 | //阻塞 61 | // <-t.wait 62 | } 63 | 64 | func (t *TaskTimer) Stop() { 65 | t.IsStop = true 66 | } 67 | 68 | /** 69 | * 用来阻塞,在start之后调用,防止主线程结束 70 | */ 71 | func (t *TaskTimer) Wait() { 72 | <-t.wait 73 | } 74 | 75 | func Test() { 76 | fmt.Println(time.Now()) 77 | } 78 | 79 | func main() { 80 | tt := CreateTaskTimer("2014-06-13 17:14:00", 1, Test) 81 | tt.Start() 82 | time.Sleep(10 * time.Second) 83 | tt.Stop() 84 | time.Sleep(10 * time.Second) 85 | } 86 | -------------------------------------------------------------------------------- /tools/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "time" 7 | ) 8 | 9 | func main() { 10 | params := os.Args 11 | if len(params) < 2 { 12 | fmt.Printf("Error:no enough arguments.\n") 13 | } 14 | 15 | switch params[1] { 16 | case "encrypt": 17 | if len(params) == 3 { 18 | encrypt(params[2]) 19 | } else { 20 | fmt.Printf("Error arguments: Need 3 args.\n") 21 | } 22 | case "sign": 23 | case "conv-time": 24 | if len(params) == 3 { 25 | unixToStanded(params[2]) 26 | } else { 27 | fmt.Printf("Error arguments: Need 3 args.\n") 28 | } 29 | case "conv-unix-time": 30 | default: 31 | } 32 | } 33 | 34 | func encrypt(str string) { 35 | pbytes := []byte(str) 36 | bytes := make([]byte, len(pbytes)) 37 | for i, b := range pbytes { 38 | bytes[i] = b ^ 3 39 | } 40 | pwd := string(bytes) 41 | 42 | fmt.Println(pwd) 43 | } 44 | 45 | func unixToStanded(str string) { 46 | t, _ := time.Parse("2006-01-02 15:04:05", str) 47 | fmt.Println(t) 48 | } 49 | -------------------------------------------------------------------------------- /web/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | "time" 8 | ) 9 | 10 | func task() { 11 | fmt.Println("task begin") 12 | time.Sleep(10 * time.Second) 13 | fmt.Println("task end") 14 | } 15 | 16 | func sayhelloName(w http.ResponseWriter, r *http.Request) { 17 | 18 | go task() 19 | fmt.Fprintf(w, "Hello") 20 | } 21 | 22 | func main() { 23 | http.HandleFunc("/test", sayhelloName) 24 | err := http.ListenAndServe(":8888", nil) 25 | if err != nil { 26 | log.Fatal("ListenAndServe:", err) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /web/main1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | ) 8 | 9 | func sayhello(w http.ResponseWriter, r *http.Request) { 10 | r.ParseForm() 11 | 12 | fmt.Println(r.Form) 13 | fmt.Println("path", r.URL.Path) 14 | fmt.Println("scheme", r.URL.Scheme) 15 | 16 | fmt.Fprintf(w, "Hello") 17 | } 18 | 19 | func main() { 20 | http.Handle("/", http.FileServer(http.Dir("./static"))) 21 | err := http.ListenAndServe(":8899", nil) 22 | if err != nil { 23 | log.Fatal("Start fail!") 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /web/mymux.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | ) 7 | 8 | type MyMux struct { 9 | } 10 | 11 | func (m *MyMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { 12 | if r.URL.Path == "/" { 13 | sayhello(w, r) 14 | return 15 | } 16 | http.NotFound(w, r) 17 | return 18 | } 19 | 20 | func sayhello1(w http.ResponseWriter, r *http.Request) { 21 | fmt.Fprintf(w, "Hello,MyMux") 22 | } 23 | 24 | // func main() { 25 | // mux := &MyMux{} 26 | // http.ListenAndServe(":8899", mux) 27 | // } 28 | -------------------------------------------------------------------------------- /web/static/aaa.txt: -------------------------------------------------------------------------------- 1 | aaaaaaaaaaaaaa -------------------------------------------------------------------------------- /web/web.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NotBadPad/go-learn/2866261cfa181c2b33815d46de3da948f2d06daa/web/web.exe -------------------------------------------------------------------------------- /zk/client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "go-learn/zk/example" 7 | "io/ioutil" 8 | "math/rand" 9 | "net" 10 | "os" 11 | "time" 12 | ) 13 | 14 | func main() { 15 | for i := 0; i < 100; i++ { 16 | startClient() 17 | 18 | time.Sleep(1 * time.Second) 19 | } 20 | } 21 | 22 | func startClient() { 23 | // service := "127.0.0.1:8899" 24 | //获取地址 25 | serverHost, err := getServerHost() 26 | if err != nil { 27 | fmt.Printf("get server host fail: %s \n", err) 28 | return 29 | } 30 | 31 | fmt.Println("connect host: " + serverHost) 32 | tcpAddr, err := net.ResolveTCPAddr("tcp4", serverHost) 33 | checkError(err) 34 | conn, err := net.DialTCP("tcp", nil, tcpAddr) 35 | checkError(err) 36 | defer conn.Close() 37 | 38 | _, err = conn.Write([]byte("timestamp")) 39 | checkError(err) 40 | 41 | result, err := ioutil.ReadAll(conn) 42 | checkError(err) 43 | fmt.Println(string(result)) 44 | 45 | return 46 | } 47 | 48 | func getServerHost() (host string, err error) { 49 | conn, err := example.GetConnect() 50 | if err != nil { 51 | fmt.Printf(" connect zk error: %s \n ", err) 52 | return 53 | } 54 | defer conn.Close() 55 | serverList, err := example.GetServerList(conn) 56 | if err != nil { 57 | fmt.Printf(" get server list error: %s \n", err) 58 | return 59 | } 60 | 61 | count := len(serverList) 62 | if count == 0 { 63 | err = errors.New("server list is empty \n") 64 | return 65 | } 66 | 67 | //随机选中一个返回 68 | r := rand.New(rand.NewSource(time.Now().UnixNano())) 69 | host = serverList[r.Intn(3)] 70 | return 71 | } 72 | 73 | func checkError(err error) { 74 | if err != nil { 75 | fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error()) 76 | os.Exit(1) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /zk/example/zkutil.go: -------------------------------------------------------------------------------- 1 | package example 2 | 3 | import ( 4 | "fmt" 5 | "github.com/samuel/go-zookeeper/zk" 6 | "time" 7 | ) 8 | 9 | const ( 10 | timeOut = 20 11 | ) 12 | 13 | var hosts []string = []string{"127.0.0.1:2183"} // the zk server list 14 | 15 | func GetConnect() (conn *zk.Conn, err error) { 16 | conn, _, err = zk.Connect(hosts, timeOut*time.Second) 17 | if err != nil { 18 | fmt.Println(err) 19 | } 20 | return 21 | } 22 | 23 | func RegistServer(conn *zk.Conn, host string) (err error) { 24 | _, err = conn.Create("/go_servers/"+host, nil, zk.FlagEphemeral, zk.WorldACL(zk.PermAll)) 25 | return 26 | } 27 | 28 | func GetServerList(conn *zk.Conn) (list []string, err error) { 29 | list, _, err = conn.Children("/go_servers") 30 | return 31 | } 32 | -------------------------------------------------------------------------------- /zk/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /** 4 | 客户端doc地址:github.com/samuel/go-zookeeper/zk 5 | **/ 6 | import ( 7 | "fmt" 8 | zk "github.com/samuel/go-zookeeper/zk" 9 | "time" 10 | ) 11 | 12 | func getConnect(zkList []string) (conn *zk.Conn) { 13 | conn, _, err := zk.Connect(zkList, 10*time.Second) 14 | if err != nil { 15 | fmt.Println(err) 16 | } 17 | return 18 | } 19 | 20 | /** 21 | * 测试连接 22 | * @return 23 | */ 24 | func test1() { 25 | zkList := []string{"localhost:2183"} 26 | conn := getConnect(zkList) 27 | 28 | defer conn.Close() 29 | conn.Create("/go_servers", nil, 0, zk.WorldACL(zk.PermAll)) 30 | 31 | time.Sleep(20 * time.Second) 32 | } 33 | 34 | /** 35 | * 测试临时节点 36 | * @return {[type]} 37 | */ 38 | func test2() { 39 | zkList := []string{"localhost:2183"} 40 | conn := getConnect(zkList) 41 | 42 | defer conn.Close() 43 | conn.Create("/testadaadsasdsaw", nil, zk.FlagEphemeral, zk.WorldACL(zk.PermAll)) 44 | 45 | time.Sleep(20 * time.Second) 46 | } 47 | 48 | /** 49 | * 获取所有节点 50 | */ 51 | func test3() { 52 | zkList := []string{"localhost:2183"} 53 | conn := getConnect(zkList) 54 | 55 | defer conn.Close() 56 | 57 | children, _, err := conn.Children("/go_servers") 58 | if err != nil { 59 | fmt.Println(err) 60 | } 61 | fmt.Printf("%v \n", children) 62 | 63 | } 64 | 65 | func main() { 66 | test3() 67 | } 68 | -------------------------------------------------------------------------------- /zk/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "go-learn/zk/example" 6 | "net" 7 | "os" 8 | "time" 9 | ) 10 | 11 | func main() { 12 | go starServer("127.0.0.1:8897") 13 | go starServer("127.0.0.1:8898") 14 | go starServer("127.0.0.1:8899") 15 | 16 | a := make(chan bool, 1) 17 | <-a 18 | } 19 | 20 | func starServer(port string) { 21 | tcpAddr, err := net.ResolveTCPAddr("tcp4", port) 22 | fmt.Println(tcpAddr) 23 | checkError(err) 24 | 25 | listener, err := net.ListenTCP("tcp", tcpAddr) 26 | checkError(err) 27 | 28 | //注册zk节点q 29 | conn, err := example.GetConnect() 30 | if err != nil { 31 | fmt.Printf(" connect zk error: %s ", err) 32 | } 33 | defer conn.Close() 34 | err = example.RegistServer(conn, port) 35 | if err != nil { 36 | fmt.Printf(" regist node error: %s ", err) 37 | } 38 | 39 | for { 40 | conn, err := listener.Accept() 41 | if err != nil { 42 | fmt.Fprintf(os.Stderr, "Error: %s", err) 43 | continue 44 | } 45 | go handleCient(conn, port) 46 | } 47 | 48 | fmt.Println("aaaaaa") 49 | } 50 | 51 | func handleCient(conn net.Conn, port string) { 52 | defer conn.Close() 53 | 54 | daytime := time.Now().String() 55 | conn.Write([]byte(port + ": " + daytime)) 56 | } 57 | 58 | func checkError(err error) { 59 | if err != nil { 60 | fmt.Fprintf(os.Stderr, "Fatal error: %s", err) 61 | os.Exit(1) 62 | } 63 | } 64 | --------------------------------------------------------------------------------