gopath 环境变量
把项目路径设置到默认的gopath下面,这样就不用去设置gopath
把项目路径设置到默认的gopath下面,这样就不用去设置gopath
最前面的是系统的用户目录,第一个就是gopath的默认目录,第二个是公司名称和用户名(这里我只写了一级),最后是项目名
下面是简单版的helloworld
package main
import "fmt"
func main() {
fmt.Println("Hello world!")
}
每一个里面只能有一个main函数,区分不同的package是根据目录来的所以每一个main函数所在的go文件都在不同的文件夹下
下面是server版的helloworld
package main
import (
"net/http"
"fmt"
)
func main() {
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
//fmt.Fprintln(writer, "<h1>Hello world!</h1>")
fmt.Fprintf(writer, "<h1>Hello world %s!", request.FormValue("name"))
})
http.ListenAndServe(":8888", nil)
}
使用 %s 这种参数就只能用Fprintf输出,localhost:8888/?name=xxx 即可访问
下面试并发版的helloworld
package main
import (
"fmt"
)
func main() {
ch := make(chan string)
// go starts a goroutine
for i := 0; i < 5000; i++ {
go printHelloWorld(i, ch)
}
for {
msg := <- ch
fmt.Println(msg)
}
//time.Sleep(time.Millisecond)
}
func printHelloWorld(i int, ch chan string) {
//fmt.Printf("Hello world from goroutine %d!\n", i)
for {
ch <- fmt.Sprintf("Hello world from goroutine %d!\n", i)
}
}
go 关键字会启动一个goroutine,这里启动了5000个,争着往chan输出helloworld,channel为同时运行的函数之间通信
提供了通道
goroutine是一个编译器级别的多任务,它和线程不一样,很多个goroutine可以同时映射到一个物理线程上去
go语言不支持函数的重载,不同函数的名字是不一样的