天天看点

go入门学习第二天 第一个go程序编写

第一个go程序编写 hello world

go脚本编写以及执行

创建项目文件 以及go脚本

脚本路径 goprojects/helloword/main.go 编写程序如下

package main

import "fmt"

func main() {
	fmt.Println("hello word")
}
           

进入脚本目录执行go命令脚本

go build main.go
           

go build 编译生成 main.go 的二进制可执行文件 main.exe

PS D:\coder\goprojects\helloword> .\main.exe 
hello word
           

windows 是 .\main.exe 在命令行界面执行 linux 和mac 都是./main 执行生成的二进制文件

也可以使用 go run 命令执行 go脚本源码看到显示结果

D:\coder\goprojects\helloword> go run main.go
hello word
           

go程序的基本结构

package main
           

这一行代码定义了 Go 中的一个包 package。包是 Go 语言的基本组成单元,通常使用单个的小写单词命名,一个 Go 程序本质上就是一组包的集合。所有 Go 代码都有自己隶属的包

func main() {
    fmt.Println("hello, world")
}
           

定义一个main 的函数

调用fmt 包中得 Println 输出内容

go语言中 使用 import 导入包路径

go mod使用场景

package main

import (
  "github.com/valyala/fasthttp"
  "go.uber.org/zap"
)

var logger *zap.Logger

func init() {
  logger, _ = zap.NewProduction()
}

func fastHTTPHandler(ctx *fasthttp.RequestCtx) {
  logger.Info("hello, go module", zap.ByteString("uri", ctx.RequestURI()))
}

func main() {
  fasthttp.ListenAndServe(":8081", fastHTTPHandler)
}
           

当前脚本功能 是调用两个第三方的包 监听8081端口,有80801的访问 会将日志打印出来

我们直接使用go编译该文件

go build main.go
main.go:4:2: no required module provides package github.com/valyala/fasthttp: go.mod file not found in current directory or any parent directory; see 'go help modules'
main.go:5:2: no required module provides package go.uber.org/zap: go.mod file not found in current directory or any parent directory; see 'go help modules'
           

编译出错提示这两个第三方的加载异常 go.mod 不存在

Go module 构建模式是在 Go 1.11 版本正式引入的,为的是彻底解决 Go 项目复杂版本依赖的问题,在 Go 1.16 版本中,Go module 已经成为了 Go 默认的包依赖管理机制和 Go 源码构建机制。

初始化go module 文件

go mod init github.com/bigwhite/hellomodule
go: creating new go.mod: module github.com/bigwhite/hellomodule
go: to add module requirements and sums:
go mod tidy
           

go mod tidy 加载配置第三方包路径

go mod tidy       
go: downloading go.uber.org/zap v1.18.1
go: downloading github.com/valyala/fasthttp v1.28.0
go: downloading github.com/andybalholm/brotli v1.0.2
... ...
           

继续回来编译go脚本

go bulid main.go
           

执行编译文件

.\main.exe
           

请求8081端口

curl localhost:8081/foo/bar
           

看到打印的监听端口的日志

PS D:\coder\goprojects\hellomodule> .\main.exe
{"level":"info","ts":1669189326.354886,"caller":"hellomodule/main.go:15","msg":"hello, go module","uri":"/foo/bar"}

           

好记性不如烂笔头,本文学自 极客时间 Tony Bai · Go 语言第一课

继续阅读