在线计算器是使用Golang开发Web服务的经典入门项目,它可以帮助我们掌握Golang基础语法、gin框架使用、HTTP接口开发以及前后端数据交互的全流程。下面我们就一步步完成这个项目的开发。

项目环境准备
首先需要在本地安装Golang环境,版本建议选择1.18及以上,然后安装gin框架作为Web开发框架。执行以下命令安装gin依赖:
go get -u github.com/gin-gonic/gin
项目结构设计
整个项目的目录结构可以设计如下:
- main.go:项目入口文件,负责启动HTTP服务
- handler/:存放接口处理逻辑的目录
- static/:存放前端静态文件的目录,包含HTML、CSS、JS文件
后端接口开发
定义计算接口
我们需要开发一个POST接口,接收前端传递的两个数字和运算符,返回计算结果。首先在handler目录下创建calc.go文件,编写计算逻辑:
package handler
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
// CalcRequest 定义请求参数结构体
type CalcRequest struct {
Num1 float64 `json:"num1" binding:"required"` // 第一个运算数
Num2 float64 `json:"num2" binding:"required"` // 第二个运算数
Operator string `json:"operator" binding:"required"` // 运算符:+ - * /
}
// CalcResponse 定义响应结构体
type CalcResponse struct {
Code int `json:"code"` // 状态码,0表示成功
Msg string `json:"msg"` // 提示信息
Result float64 `json:"result"` // 计算结果
}
// CalcHandler 处理计算请求
func CalcHandler(c *gin.Context) {
var req CalcRequest
// 绑定请求参数
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, CalcResponse{
Code: -1,
Msg: "参数解析失败,请检查请求格式",
Result: 0,
})
return
}
var result float64
var errMsg string
// 根据运算符执行对应计算
switch req.Operator {
case "+":
result = req.Num1 + req.Num2
case "-":
result = req.Num1 - req.Num2
case "*":
result = req.Num1 * req.Num2
case "/":
if req.Num2 == 0 {
errMsg = "除数不能为0"
} else {
result = req.Num1 / req.Num2
}
default:
errMsg = "不支持的运算符,仅支持+-*/"
}
// 处理异常情况
if errMsg != "" {
c.JSON(http.StatusOK, CalcResponse{
Code: -1,
Msg: errMsg,
Result: 0,
})
return
}
// 返回成功结果
c.JSON(http.StatusOK, CalcResponse{
Code: 0,
Msg: "计算成功",
Result: result,
})
}
入口文件编写
在main.go中注册路由并启动服务:
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"your_project/handler" // 替换为你的项目模块路径
)
func main() {
// 创建gin引擎
r := gin.Default()
// 配置静态文件服务,前端文件放在static目录下
r.Static("/static", "./static")
// 配置根路径访问前端页面
r.LoadHTMLGlob("static/*")
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", nil)
})
// 注册计算接口
r.POST("/api/calc", handler.CalcHandler)
// 启动服务,监听8080端口
r.Run(":8080")
}
前端页面开发
在static目录下创建index.html文件,编写计算器的前端页面:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>在线计算器</title>
<style>
.calc-container {
width: 300px;
margin: 50px auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 8px;
}
.input-group {
margin-bottom: 15px;
}
.input-group label {
display: block;
margin-bottom: 5px;
}
.input-group input, .input-group select {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
.btn {
width: 100%;
padding: 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.result {
margin-top: 15px;
padding: 10px;
background-color: #f8f9fa;
border-radius: 4px;
}
</style>
</head>
<body>
<div class="calc-container">
<h2>在线计算器</h2>
<div class="input-group">
<label>第一个数:</label>
<input type="number" id="num1" step="any">
</div>
<div class="input-group">
<label>运算符:</label>
<select id="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
</div>
<div class="input-group">
<label>第二个数:</label>
<input type="number" id="num2" step="any">
</div>
<button class="btn" onclick="calculate()">计算</button>
<div class="result" id="result">结果:</div>
</div>
<script>
function calculate() {
const num1 = parseFloat(document.getElementById('num1').value);
const num2 = parseFloat(document.getElementById('num2').value);
const operator = document.getElementById('operator').value;
const resultDiv = document.getElementById('result');
// 参数校验
if (isNaN(num1) || isNaN(num2)) {
resultDiv.innerText = '结果:请输入有效的数字';
return;
}
// 发送请求到后端接口
fetch('/api/calc', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
num1: num1,
num2: num2,
operator: operator
})
})
.then(response => response.json())
.then(data => {
if (data.code === 0) {
resultDiv.innerText = '结果:' + data.result;
} else {
resultDiv.innerText = '结果:' + data.msg;
}
})
.catch(error => {
resultDiv.innerText = '结果:请求失败,请稍后重试';
});
}
</script>
</body>
</html>
项目运行与测试
完成所有代码编写后,在项目根目录执行以下命令启动服务:
go run main.go
服务启动后,打开浏览器访问http://127.0.0.1:8080,就可以看到计算器的前端页面。输入两个数字,选择对应的运算符,点击计算按钮,前端会调用后端接口完成计算并展示结果。如果出现除数为0或者输入不支持的运算符,页面也会展示对应的错误提示。
功能扩展建议
完成基础功能后,还可以对这个项目进行扩展:
- 增加开方、平方、取模等更多运算类型
- 添加计算历史记录功能,把每次计算的结果存储到内存或文件中
- 增加参数校验,比如限制输入数字的范围
- 添加接口鉴权,避免接口被恶意调用
Golanggin在线计算器http_server修改时间:2026-06-30 00:18:24