[goLang]Gin框架 hello world

文章介绍了如何配置Go的代理以加快包下载速度,特别是使用goproxy.io和goproxy.cn。接着展示了使用gin框架创建一个简单的HTTP服务器,包括处理GET请求和返回JSON响应。此外,还提到了加载HTML模板并运行服务时遇到的404错误问题,强调了gin框架中`Run`方法的位置重要性,应置于最后。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先要配置代理,就像maven配置国内源一样,有效提升下载速度

GOPROXY=https://goproxy.io

 然后就可以执行

go get -u github.com/gin-gonic/gin

 如果还是报错超时, 那么可以先执行一下两条命令再次重试下载

go env -w GOPROXY=https://goproxy.cn,direct
go mod tidy

效果如下:

package main

import "github.com/gin-gonic/gin"

func main() {
	//创建一个服务
	ginServer := gin.Default()

	//创建GET请求
	ginServer.GET("hello", func(context *gin.Context) {
		//响应code,返回内容
		context.JSON(200, gin.H{"msg": "hello world"})
	})

	//端口
	ginServer.Run(":8888")
}

postman测试:(也可以直接在浏览器访问. )

----------------------------------

返回前端页面:

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	//创建一个服务
	ginServer := gin.Default()

	//全局加载页面
	ginServer.LoadHTMLGlob("templates/*")
	//指定加载
	//ginServer.LoadHTMLFiles("templates/index.html")

	//html
	ginServer.GET("index", func(context *gin.Context) {
		context.HTML(http.StatusOK, "index.html", gin.H{
			"msg": "这是来自go后端传输的数据",
		})
	})
	//端口
	ginServer.Run(":8888")
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>my first page</title>
</head>
<body>
<h1>hello wsc</h1>
获取内容:
{{.msg}}
</body>
</html>

项目文件目录如下:

访问localhost:8888/index

 

另外还发现一个问题, 如果端口设置(ginServer.Run(":8888"))放在GET请求前面会导致404报错... 

看了另一位小哥的文章发现 gin配置的Run方法一定要放在最后...

gin——请求返回404原因_gin 404_折叠的饼干的博客-优快云博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值