02. 一个例子熟悉Go
2019-05-29 本文已影响0人
大鱼人Echo
Go工具/命令
build: compile packages and dependencies
- 最常用的go command之一, 编译go文件
- 跨平台编译: env GOOS=linux GOARCH=amd64 go build
install: compile and install packages and dependencies
- 也是编译,与build最大的区别是编译后会将输出文件打包成库放在pkg下
- 常用于本地打包编译命令: go install
get: download and install packages and dependencies
- 用于获取go的第三方包, 通常会默认从git repo 上pull最新的版本
- 常用命令如: go get -u github.com/go-sql-driver/mysql(从github上获取mysql的driver并安装至本地)
fmt: gofmt(reformat) package sources
- 类似于C中的lint, 统一代码风格和排版
- 常用命令如: go fmt
test: test packages
- 运行当前包目录下的tests
- 常用命令如: go test 或go test -v等
- Go的test一般以XXX_test.go为文件名
- XXX的部分一般为XXX_test.go所要测试的代码文件名。注: Go并没有特别要求XXX的部分必须是要测试的文件名
## 目录结构
├── main.go
└── main_test.go
package main
import (
"io"
"net/http"
)
// Print1to20 答应1到20的和
func Print1to20() int {
res := 0
for i := 1; i <= 20; i++ {
res += i
}
return res
}
func firstPage(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "<h1>Hello, this is my first page!</h1>")
}
func main() {
http.HandleFunc("/", firstPage)
http.ListenAndServe(":8000", nil)
}
package main
import (
"fmt"
"testing"
)
func TestPrint(t *testing.T) {
res := Print1to20()
fmt.Println("hey")
if res != 210 {
t.Errorf("Wrong result of Print1to20")
}
}
go test -v