web前端调用go后端api
首先要明确:Go本身没有“前端直接调用”的专属框架(因为前端和后端是跨端的,本质是通过HTTP/HTTPS网络协议通信),但Go生态有大量成熟的框架用于快速构建RESTful API服务,前端(如Vue/React/原生JS)可通过标准的HTTP请求(GET/POST/PUT/DELETE等)调用这些API。
下面是Go中最常用的API开发框架及使用示例:
1. 标准库 net/http(无第三方依赖)
Go内置的net/http包就可以构建基础的API服务,无需安装任何第三方框架,适合简单场景。
package main
import (
"encoding/json"
"log"
"net/http"
)
// 定义API返回的数据结构
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
// 处理GET请求的API接口
func helloHandler(w http.ResponseWriter, r *http.Request) {
// 设置响应头(允许跨域,否则前端会报跨域错误)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*") // 生产环境需限定具体域名
// 构造返回数据
resp := Response{
Code: 200,
Message: "success",
Data: "Hello, 前端调用Go后端API成功!",
}
// 将数据转为JSON并返回
json.NewEncoder(w).Encode(resp)
}
func main() {
// 注册API路由
http.HandleFunc("/api/hello", helloHandler)
// 启动HTTP服务,监听8080端口
log.Println("服务器启动:http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
2. 主流第三方框架(高性能、易用)
对于复杂项目,推荐使用第三方框架,性能和开发效率更高:
(1)Gin(最主流、高性能)
Gin是Go生态中最火的Web框架,基于httprouter,性能极高,API设计简洁,适合构建RESTful API。
安装Gin:
go get -u github.com/gin-gonic/gin
Gin实现API示例:
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
// 创建Gin引擎(开发模式)
r := gin.Default()
// 解决跨域问题(中间件)
r.Use(func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
c.Header("Access-Control-Allow-Headers", "Content-Type,Authorization")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
})
// 定义API路由组
api := r.Group("/api")
{
// GET请求
api.GET("/hello", func(c *gin.Context) {
c.JSON(200, gin.H{
"code": 200,
"message": "success",
"data": "Gin框架API响应",
})
})
// POST请求(接收前端参数)
api.POST("/user", func(c *gin.Context) {
// 定义接收参数的结构体
type User struct {
Username string `json:"username" binding:"required"`
Age int `json:"age" binding:"required,gt=0"`
}
var user User
// 解析前端传入的JSON参数
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(400, gin.H{
"code": 400,
"message": "参数错误",
"data": err.Error(),
})
return
}
// 业务逻辑处理...
// 返回响应
c.JSON(200, gin.H{
"code": 200,
"message": "用户创建成功",
"data": user,
})
})
}
// 启动服务
r.Run(":8080") // 监听8080端口
}
(2)其他常用框架
- Echo:和Gin类似,高性能,极简设计,API风格更接近Express(Node.js框架),适合熟悉Node.js的开发者。
- Fiber:基于Fasthttp(比标准库http快10倍以上),API设计完全模仿Express,性能极致,适合高并发场景。
- Beego:全栈框架,包含ORM、MVC、API文档等一站式功能,适合快速开发中小型项目,但相对重一些。
3. 前端调用Go后端API示例(原生JS)
无论你用哪种Go框架构建API,前端都可以通过fetch/axios等工具调用,示例如下:
// 调用GET接口
fetch('http://localhost:8080/api/hello')
.then(response => response.json())
.then(data => {
console.log('GET请求响应:', data);
// 渲染到页面
document.body.innerText = data.data;
})
.catch(error => console.error('请求失败:', error));
// 调用POST接口
fetch('http://localhost:8080/api/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username: '张三', age: 20 }),
})
.then(response => response.json())
.then(data => console.log('POST请求响应:', data))
.catch(error => console.error('请求失败:', error));
总结
- Go没有“前端直接调用”的框架,前端调用Go后端API的核心是HTTP网络通信,Go的作用是构建符合HTTP标准的API服务。
- 简单场景用标准库
net/http,复杂项目优先选Gin(生态最完善),高并发场景可考虑Fiber/Echo。 - 开发时必须处理跨域(CORS) 问题,否则前端会因浏览器同源策略限制无法调用API。

浙公网安备 33010602011771号