// 1.多goroutine间通信,channel使用 import ( "fmt" "math/rand" "net" "os" "os/signal" "time" "crypto/sha256" "crypto/sha1" "crypto/md5" "strings" ) func Producer(queue chan<- int) { for i := 0; i < 10; i++ { queue <- i fmt.Println("Create: ", i) } } func Consumer(queue <-chan int) { for i := 0; i < 10; i++ { v := <-queue fmt.Println("Receive: ", v) } } func main() { queue := make(chan int, 100) Producer(queue) Consumer(queue) time.Sleep(10 * time.Second) } // 2、信号使用 func SignalTest() { timeStart := time.Now() c := make(chan os.Signal) signal.Notify(c, os.Kill, os.Interrupt) s := <-c timeEnd := time.Now().Sub(timeStart) fmt.Println("Receive Signal: ", s) fmt.Println("耗时: ", timeEnd) } // 3、获取路径 func GetWd() { wd, err := os.Getwd() if err != nil { fmt.Println("Getwd Fail[Err:%s]", err.Error()) return } fmt.Println(wd) } // 4、随机数 func GetRand() { r := rand.New(rand.NewSource(time.Now().UnixNano())) r.Intn(100) // 0~100内随机数 } // 5、tcp连接 func GetConn() { conn, err := net.Dial("tcp", "localhost:8080") if err != nil { fmt.Println("Get Tcp Conn Fail[Err:%s]", err.Error()) return } fmt.Println("连接服务器成功") defer conn.Close() ProConn(conn) } func ProConn(conn net.Conn) { sms := "hello world" conn.Write([]byte(sms)) // 字符串转换为byte buf := make([]byte, 10) c, err := conn.Read(buf) if err != nil { fmt.Println("Read Fail[Err:%s]", err.Error()) return } fmt.Printf("Read Message %s", buf[0:c]) } // 摘要 // sha256 func Digest(){ msg := "my password" h := sha256.New() h.Write([]byte(msg)) fmt.Println(h.Sum(nil)) // sha1 h = sha1.New() h.Write([]byte(msg)) fmt.Println(h.Sum(nil)) // md5 h = md5.New() h.Write([]byte(msg)) fmt.Println(h.Sum(nil)) } // 闭包 func UseAdder() { var f = Adder() fmt.Println(f(1), "-") fmt.Println(f(20), "-") fmt.Println(f(300), "-") } func Adder() func(int) int { var x int return func(delta int) int { x += delta return x } }