[Go实战]第三章-开始编码-笔记
一. godoc 使用
1:安装 godoc
命令:go get golang.org/x/tools/cmd/godoc
2:运行 godoc
命令:godoc --http=:6060
3:浏览器访问:localhost:6060
mac环境下如果执行上面👆的安装命令后命令行中依然后提示
command not found: godoc
, 这是因为下载的godoc 被安装到了 $GOPATH 下的bin中,需要手动建立软连接👉:ln -s $GOPATH/bin/godoc Usr/local/bin/godoc
二. Go自动重载组件 air 使用
1:设置 goproxy
国内代理:go env -w GOPROXY=https://goproxy.cn
2:安装 air 组件:go get -u github.com/cosmtrek/air
如果只为当前命令启用 Go Module,则使用命令
GO111MODULE=on go get -u github.com/cosmtrek/air
3:检测air 是否安装成功:air -v
。如果执行此命令后提示 command not found: air
。 进入到 $GOPATH/bin目录下,看是否存在 air。如果存在,则建立软连接:ln -s $GOPATH/bin/air Usr/local/bin/air
4:在项目目录下的命令行中执行 air
三. main.go 源码
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
requestPath := request.URL.Path
var content string
if requestPath == "/" {
content = "<h1>Hello this is Golang!</h1>"
} else if requestPath == "/about" {
content = "<h1>this is about page :)👌haha</h1>"
} else {
content = "<h1>404, this page is not found</h1>"
writer.WriteHeader(http.StatusNotFound)
}
writer.Header().Set("Content-Type", "text/html; charset=utf-8")
writer.WriteHeader(http.StatusOK)
writer.Write([]byte(requestPath + "\n"))
writer.Write([]byte(content))
})
http.HandleFunc("/page", HandlePage)
http.ListenAndServe(":3030", nil)
}
func HandlePage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, r.Header.Get("User-Agent"))
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: