美文网首页
go's helloWorld

go's helloWorld

作者: bocsoft | 来源:发表于2018-12-24 15:24 被阅读0次
    package main
    
    import (
        "fmt"
        "net/http"
        "time"
    )
    
    func main() {
        //原始版
        helloWorld1()
        //http版
        helloWorld2()
        // go 协程版
        for i := 0; i < 5; i++ {
            go helloWorld3(i)
        }
        time.Sleep(time.Microsecond) // 添加延时,协程才有机会在main()主协程退出前执行
    
        //go + channel
        ch := make(chan string)
        for i := 0; i < 5; i++ {
            go helloWorld4(i, ch)
        }
        for {
            msg := <-ch
            fmt.Println(msg)
        }
    
    }
    
    func helloWorld1() {
        fmt.Println("hello world")
    }
    
    func helloWorld2() {
        http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
            fmt.Fprintf(writer, "<h1>hello world %v</h1>", request.FormValue("name"))
        })
        http.ListenAndServe(":8888", nil)
    }
    
    func helloWorld3(i int) {
        fmt.Printf("hello world from goroutine %v \n", i)
    }
    
    func helloWorld4(i int, ch chan string) {
        for {
            ch <- fmt.Sprintf("hello world %v", i)
        }
    }
    
    
    
    

    相关文章

      网友评论

          本文标题:go's helloWorld

          本文链接:https://www.haomeiwen.com/subject/iyjzkqtx.html