1.go的安装
1.1 确认版本go version
go version go1.20.4 darwin/amd64 可以看到是macos10.14版本。如果是m1 需要安装对应的版本
1.2 用vscode 进行编写go的简单例子
先进入vscode的界面,新建一个目录为godemo,里面就是go的例子的工作目录,建立一个hello.go的文件,将下面的代码拷贝到hello.go 文件里面
保存文件
package mainimport ("fmt"
)func main() {// 打印 "Hello, World!"fmt.Println("Hello, World!")
}
vscode 直接点击F5 运行是会报错
按照提示,需要安装一下环境内容,直接点击install 按键,安装看看。
提示安装成功
VSCode 带版本比较功能,这里先可以忽略掉
继续点击F5的时候,直接会提示缺失go.mod的内容
新建一个终端,查看目录下缺失一个文件go.mod的文件。
建立一个go.mod
go mod init example.com/v2go mod tidy
vscode F5就可以直接运行和调试
或者用终端上运行go run hello.go 也可以得到结果
go run hello.go
Hello, World!
Gin Web Framework
先安装 ,查看安装实际是直接拉取的代码
go get -u github.com/gin-gonic/gin
go: downloading github.com/gin-gonic/gin v1.9.0
go: downloading golang.org/x/net v0.7.0
go: downloading github.com/go-playground/validator/v10 v10.11.2
go: downloading github.com/mattn/go-isatty v0.0.19
go: downloading github.com/pelletier/go-toml/v2 v2.0.8
go: downloading github.com/ugorji/go/codec v1.2.9
go: downloading github.com/go-playground/validator/v10 v10.14.0
go: downloading golang.org/x/net v0.10.0
go: downloading github.com/ugorji/go/codec v1.2.11
go: downloading google.golang.org/protobuf v1.30.0
go: downloading github.com/bytedance/sonic v1.8.0
go: downloading github.com/ugorji/go v1.2.11
go: downloading github.com/goccy/go-json v0.10.2
go: downloading golang.org/x/sys v0.5.0
go: downloading github.com/bytedance/sonic v1.9.0
go: downloading github.com/go-playground/universal-translator v0.18.1
go: downloading golang.org/x/sys v0.8.0
go: downloading golang.org/x/text v0.7.0
go: downloading github.com/leodido/go-urn v1.2.4
go: downloading golang.org/x/crypto v0.9.0
go: downloading golang.org/x/text v0.9.0
go: downloading github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311
go: downloading github.com/twitchyliquid64/golang-asm v0.15.1
go: downloading golang.org/x/arch v0.0.0-20210923205945-b76863e36670
go: downloading github.com/klauspost/cpuid/v2 v2.0.9
go: downloading golang.org/x/arch v0.3.0
go: downloading github.com/klauspost/cpuid v1.3.1
go: downloading github.com/klauspost/cpuid/v2 v2.2.4
go: downloading github.com/gabriel-vasile/mimetype v1.4.2
go: added github.com/bytedance/sonic v1.9.0
go: added github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311
go: added github.com/gabriel-vasile/mimetype v1.4.2
go: added github.com/gin-contrib/sse v0.1.0
go: added github.com/gin-gonic/gin v1.9.0
go: added github.com/go-playground/locales v0.14.1
go: added github.com/go-playground/universal-translator v0.18.1
go: added github.com/go-playground/validator/v10 v10.14.0
go: added github.com/goccy/go-json v0.10.2
go: added github.com/json-iterator/go v1.1.12
go: added github.com/klauspost/cpuid/v2 v2.2.4
go: added github.com/leodido/go-urn v1.2.4
go: added github.com/mattn/go-isatty v0.0.19
go: added github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd
go: added github.com/modern-go/reflect2 v1.0.2
go: added github.com/pelletier/go-toml/v2 v2.0.8
go: added github.com/twitchyliquid64/golang-asm v0.15.1
go: added github.com/ugorji/go/codec v1.2.11
go: added golang.org/x/arch v0.3.0
go: added golang.org/x/crypto v0.9.0
go: added golang.org/x/net v0.10.0
go: added golang.org/x/sys v0.8.0
go: added golang.org/x/text v0.9.0
go: added google.golang.org/protobuf v1.30.0
go: added gopkg.in/yaml.v3 v3.0.1
用gin框架编写一个最简单额web服务。实现输出hello world json串
package mainimport ("net/http""github.com/gin-gonic/gin"
)func main() {r := gin.Default()r.GET("/ping", func(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"message": "pong",})})r.GET("/", func(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"hello": "world",})})r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
访问地址不同,返回不同结果
后台运行的结果图片是,说明路径已经绑定了/ping 和/ 访问不同的路径,返回不同的结果
go run example.go
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.- using env: export GIN_MODE=release- using code: gin.SetMode(gin.ReleaseMode)[GIN-debug] GET /ping --> main.main.func1 (3 handlers)
[GIN-debug] GET / --> main.main.func2 (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080
[GIN] 2023/05/28 - 20:28:03 | 200 | 49.187µs | 127.0.0.1 | GET "/"
返回的是hello world
返回的是message pong
建立的Go socket的server.go
package mainimport ("flag""log""text/template""github.com/gin-gonic/gin""github.com/gorilla/websocket"
)var addr = flag.String("addr", ":8080", "http service address")var upgrader = websocket.Upgrader{} // use default optionfunc echo(ctx *gin.Context) {w, r := ctx.Writer, ctx.Requestc, err := upgrader.Upgrade(w, r, nil)if err != nil {log.Println("upgrade:", err)return}defer c.Close()for {mt, message, err := c.ReadMessage()if err != nil {log.Println("read:", err)break}log.Printf("recv:%s", message)err = c.WriteMessage(mt, message)if err != nil {log.Println("write:", err)break}}
}func home(c *gin.Context) {homeTemplate.Execute(c.Writer, "ws://"+c.Request.Host+"/echo")
}func main() {flag.Parse()log.SetFlags(0)r := gin.Default()r.GET("/echo", echo)r.GET("/", home)log.Fatal(r.Run(*addr))
}var homeTemplate = template.Must(template.New("").Parse(`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
window.addEventListener("load", function(evt) {var output = document.getElementById("output");var input = document.getElementById("input");var ws;var print = function(message) {var d = document.createElement("div");d.textContent = message;output.appendChild(d);output.scroll(0, output.scrollHeight);};document.getElementById("open").onclick = function(evt) {if (ws) {return false;}ws = new WebSocket("{{.}}");ws.onopen = function(evt) {print("OPEN");}ws.onclose = function(evt) {print("CLOSE");ws = null;}ws.onmessage = function(evt) {print("RESPONSE: " + evt.data);}ws.onerror = function(evt) {print("ERROR: " + evt.data);}return false;};document.getElementById("send").onclick = function(evt) {if (!ws) {return false;}print("SEND: " + input.value);ws.send(input.value);return false;};document.getElementById("close").onclick = function(evt) {if (!ws) {return false;}ws.close();return false;};
});
</script>
</head>
<body>
<table>
<tr><td valign="top" width="50%">
<p>Click "Open" to create a connection to the server,
"Send" to send a message to the server and "Close" to close the connection.
You can change the message and send multiple times.
<p>
<form>
<button id="open">Open</button>
<button id="close">Close</button>
<p><input id="input" type="text" value="Hello world!">
<button id="send">Send</button>
</form>
</td><td valign="top" width="50%">
<div id="output" style="max-height: 70vh;overflow-y: scroll;"></div>
</td></tr></table>
</body>
</html>
`))
开启服务,关闭服务,发送消息,点击发送
websocket 可以发送消息,服务开启后可以进行发送。