Go语言实战流媒体视频网站(2.1)

328 阅读1分钟

一个例子了解GO

Go有如下命令:

Go is a tool for managing Go source code.

Usage:

	go <command> [arguments]

The commands are:

	bug         start a bug report
	build       compile packages and dependencies
	clean       remove object files and cached files
	doc         show documentation for package or symbol
	env         print Go environment information
	fix         update packages to use new APIs
	fmt         gofmt (reformat) package sources
	generate    generate Go files by processing source
	get         download and install packages and dependencies
	install     compile and install packages and dependencies
	list        list packages or modules
	mod         module maintenance
	run         compile and run Go program
	test        test packages
	tool        run specified go tool
	version     print Go version
	vet         report likely mistakes in packages

下面介绍一下常用的命令:

build       compile packages and dependencies
最常用的go command之一,编译go文件

跨平台编译: env  GOOS=linux GOARCH=ARM64 go build
GOOS:目标操作系统
GOARCH:目标kernel
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并安装到本地, -u表示下载最新的)
fmt         gofmt (reformat) package sources
统一代码风格和排版
常用命令:go fmt
test        test packages
运行当前包目录下的tests
常用命令:
	go test: 打印测试结果
	go test -v: 打印测试过程和结果

测试文件命名
/* main.go
/* main_test.go
test一般以XXX_test.go为文件名,后缀_test.go不要写错了,否则会报错

下面举例子说明:main.go

package main

import (
  "io"
  "net/http"
)

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>Hi, lady-killer!</h1>")
}

func main(){
  http.HandleFunc("/", firstPage)
  http.ListenAndServe(":8000", nil)
}

main_test.go

package main

import (
  "testing"
  "fmt"
)

func TestPrint(t *testing.T){
  res := Print1to20()
  fmt.Println("testing")
  if res != 210{
    t.Errorf("Result Worng!")
  }
}