GO的服务

article/2025/7/9 5:54:38

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 可以发送消息,服务开启后可以进行发送。

 


http://chatgpt.dhexx.cn/article/LVCYjOFJ.shtml

相关文章

Go Registry

实现微服务的服务注册中心&#xff0c;支持服务服务注册、接收心跳等。客户端实现基于注册中心的服务发现机制 微服务 微服务是一些协同工作的小而自治的服务 微服务主要分为六个部分组成 服务描述&#xff1a;类似服务的文档说明&#xff0c;简单但不可或缺。 比如&#xff1a…

Gogs私服搭建

1. Gogs介绍 官网地址&#xff1a;https://gogs.io 文档地址&#xff1a;https://gogs.io/docs Gogs&#xff0c;全称为Go Git Service&#xff0c;是一个基于 Go 语言开发的Git服务。它提供了一个类似于GitHub的界面和功能&#xff0c;允许您在自己的服务器上搭建私有的Git仓库…

vhost-user

1&#xff0c;virtqueue 图一 每个queue实际上是由tx/rx两个virtqueue组成的也就是说tx和rx的virtqueue是分开的&#xff0c;并没有共享。一个virtio net设备最多有多少个queue由后端vhost决定&#xff0c;但前端可以通过ethtool –L eth0 combined 16命令动态修改当前队列数&…

gohost -- go 开发的命令行hosts配置管理工具

前几天在微博上看到有人推荐了lazygit这个工具&#xff0c;让人眼前一亮&#xff0c;什么时候命令行也可以这么抢到了&#xff0c;?&#xff0c;调研了下&#xff0c;发现它使用了gocui&#xff0c;使用它可以做出来很多很炫的命令行工具。 现有的hosts工具里面也有switchosts…

Android studio占用C盘资源的解决方法

Android studio占用C盘资源的解决方法 Android Studio安装成功后会在系统盘用户目录下产生这几个文件夹 一、目录介绍 1、.android 是Android SDK生成的AVD&#xff08;Android Virtual Device Manager&#xff09;即模拟器存放路径 2、.AndroidStudio4.0&#xff08;这里我安…

Minecraft神奇玩家不用键盘,行走全部靠骑猪最后通关MC

大家好&#xff0c;在Minecraft中有非常多的玩法&#xff0c;但是您听说过全程游戏不用键盘只用鼠标通关的玩法吗&#xff1f;也就是说在游戏中不能使用WSAD和空格按键通关&#xff01;这听起来简直就是天方夜谈了&#xff01; 在国外有位玩家叫做HeightAdvantage的玩家&#…

2021大树分享收集的网盘搜索站给兄弟们

聚合网盘搜索 https://www.chaonengso.com/ 某柠檬 https://www.moulem.com/ 史莱姆 http://www.slimego.cn/ 蓝菊花-城通网盘 http://www.lanjuhua.com google Drive搜索引擎 https://gezhong.vip/ 陈蛋蛋的宝藏库 http://www.chendandan.ys168.com/ xx资料网 https://www.xxu…

WPF窗体最小化到任务栏

WPF程序也可以很轻松的实现类似QQ那样最小化到任务栏的功能。 WindowState ws;WindowState wsl;NotifyIcon notifyIcon;

android ip格式化输入法,手机键盘还能这样玩?简单几步,让你的输入法萌动可人!...

玩手机&#xff0c;打字忙&#xff0c;输入法你用的是原厂、还是第三方&#xff1f;相信大多数网友跟我一样&#xff0c;换了新手机&#xff0c;会在第一时间安装自己习惯的第三方输入法。 相对而言&#xff0c;我更喜欢百度输入法&#xff0c;它的优势之一便是拥有种类丰富、脑…

渗透测试 ( 1 ) --- 相关术语、必备 工具、导航、全流程总结、入侵网站思路

From&#xff1a;https://zhuanlan.zhihu.com/p/401413938 渗透测试实战教学&#xff1a;https://www.zhihu.com/column/c_1334810805263515648 导航类网站&#xff1a; 渗透师网络安全从业者安全导航&#xff08;速查小手册&#xff09;​ 渗透师导航&#xff1a;https…

csgo原始输入开不开_CSGO职业哥参数配置:帅气猪猪JW

在CSGO游戏中,狙击手一直都扮演着团队中非常重要的位置,无论是进攻还是防守,利用狙击的远距击杀,不仅能够造成人数上面的领先,同时还可以打乱对方的战术安排部署,是真正的牵一发而动全身的关键位置。 那么,我们今天来介绍的是这么一位狙击手,CSGO圈中是这么评价他的:在…

dialog dismiss时键盘不消失的问题。

当setCanceledOnTouchOutside(true)&#xff0c;点击阴影处&#xff0c;dialog dismiss时键盘不消失的问题。 一开始觉得很简单&#xff0c;监听下onDimiss&#xff08;&#xff09;方法&#xff0c;在里面隐藏键盘不就行了。 但是发现大多数手机都不会隐藏&#xff08;魅族x4…

pe没法给服务器装系统吗,U盘重装系统无法进入PE解决方法

使用U盘启动盘重装系统&#xff0c;进不去PE怎么办&#xff1f;制作好U盘启动盘&#xff0c;准备装系统的时候&#xff0c;遇到不能进入PE的情况该怎么解决&#xff1f;下面小编整理一篇教程&#xff0c;帮助大家解决这个问题。 首先先分析u盘装系统不能进入pe的原因&#xff1…

真正的黑客键盘

IT程序猿 微博网友评论&#xff1a; 金先生不睡觉&#xff1a;甚至没有退格键&#xff01; O2酱&#xff1a;复读机的键盘&#xff1a;Ctrl&#xff0c;C&#xff0c;V 蓝天草地生活&#xff1a;高手专用&#xff01; 吴彦猪猪_yzy&#xff1a;其实不需要done 某个序列表示don…

LeetCode500. 键盘行

项目场景&#xff1a; 行百里路者半九十 问题描述 键盘行 给你一个字符串数组 words &#xff0c;只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。 美式键盘 中&#xff1a; 第一行由字符 “qwertyuiop” 组成。 第二行由字符 “asdfghjkl” 组成…

又一款度盘不限速下载神器,无需登录,10M/s!

开局一张图 这是我最新发现的一款百度云下载工具 简介 有一个网站叫 6盘&#xff0c;这个网站呢&#xff0c;可以转存百度网盘的资源。 然后再将转存的文件下载就可以不限速下载了。 然后&#xff0c;工具的作者觉得 6盘网页版还行&#xff0c;PC版丑拒。 于是&#xff0c;一时…

推荐6款珍藏已久的网盘搜索工具

最近收集了几款好用的网盘资源搜索网站&#xff0c;可能你已经在用了&#xff0c;可能你还不知道它的存在 。如果你已经在用了&#xff0c;说明你很有远光&#xff0c;好的搜索网盘将大大提高我们平时的搜索资源的效率 。 1 胖次搜索 胖次网盘搜索引擎,独家的索引挖掘技术,为您…

深度linux没有硬盘,安装Deepin系统到硬盘分区部分没有发现硬盘数据的解决

使用华为笔记本安装Deepin系统非常的顺利&#xff0c;但是在使用戴尔笔记本安装Deepin的时候却不那么如意&#xff0c;在安装到选择语言后&#xff0c;进展到硬盘分区部分&#xff0c;却没有发现硬盘数据&#xff0c;如下图所示&#xff0c;没有任何的数据&#xff0c;这里就不…

设计模式六大原则

前言&#xff0c;最近参加了面试&#xff0c;问道了设计模式的六大原则&#xff0c;当时一阵尴尬&#xff0c;现在总结一下&#xff0c;设计模式的六大原则如下&#xff1a; 定义&#xff1a;一个软件实体如类、模块和函数应该对扩展开放&#xff0c;对修改关闭 …