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)
}
}
网友评论