- Webアプリ
- YouTubeはGoで書かれている
- ソフトウェア
- Windows, Linux, Macを同じコードで書ける
- Android, iOSを同じコードで書ける
- PaaS
- Docker, KubernetesはGoで書かれている
並列処理が簡単に書ける!!!!!
-
6s.go
func main() { log.Print("-- start") log.Print("1s") time.Sleep(1 * time.Second) log.Print("done") log.Print("2s") time.Sleep(2 * time.Second) log.Print("done") log.Print("3s") time.Sleep(3 * time.Second) log.Print("done") log.Print("-- finish") }
- 3s.go
func main() {
log.Print("-- start")
finished := make(chan bool)
tasks := []func(){
func() {
log.Print("1s")
time.Sleep(1 * time.Second)
log.Print("done")
finished <- true
},
func() {
log.Print("2s")
time.Sleep(2 * time.Second)
log.Print("done")
finished <- true
},
func() {
log.Print("3s")
time.Sleep(3 * time.Second)
log.Print("done")
finished <- true
},
}
for _, task := range tasks {
go task()
}
for i := 0; i < len(tasks); i++ {
<-finished
}
log.Print("-- finish")
}
- 3skai.go
func main() {
log.Print("-- start")
tasks := []func(){
sleep(1),
sleep(2),
sleep(3),
}
var wg sync.WaitGroup
for _, task := range tasks {
wg.Add(1)
go func(f func()) {
defer wg.Done()
f()
}(task)
}
wg.Wait()
log.Print("-- finish")
}
func sleep(sec int) func() {
return func() {
log.Printf("%ds", sec)
time.Sleep(time.Duration(sec) * time.Second)
log.Printf("%d done", sec)
}
}
-
server.go
package main import ( "fmt" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World") } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
たったこれだけ!!!
-
dos.go
package main import ( "log" "net/http" "sync" "time" ) func main() { url := "http://localhost:8080" maxConnection := make(chan bool, 100) var wg sync.WaitGroup count := 0 start := time.Now() for maxRequest := 0; maxRequest < 10000; maxRequest++ { wg.Add(1) maxConnection <- true go func() { defer wg.Done() resp, err := http.Get(url) if err != nil { return } defer resp.Body.Close() count++ <- maxConnection }() } wg.Wait() end := time.Now() log.Printf("%d 回のリクエストに成功しました!\n", count) log.Printf("%f 秒処理に時間がかかりました!\n", (end.Sub(start)).Seconds()) }