答案:使用Golang标准库开发一个简易在线计算器,通过net/http处理路由和请求,前端HTML表单提交数据,后端解析并计算结果并渲染回页面,支持加减乘除运算并进行基础错误处理,项目结构清晰,适合Web和Go语言入门学习。

用Golang开发一个小型在线计算器,可以作为学习Web基础和Go语言实践的入门项目。这个项目不需要复杂的依赖,只需标准库就能完成前后端逻辑。
整个项目结构简单清晰,便于维护和扩展:
使用net/http包启动Web服务,定义两个路由:/ 显示计算器页面,/calculate 处理计算请求。
核心代码示例如下:
立即学习“go语言免费学习笔记(深入)”;
package main
<p>import (
"html/template"
"log"
"net/http"
"strconv"
)</p><p>type Result struct {
Value string
}</p><p>func indexHandler(w http.ResponseWriter, r *http.Request) {
tmpl, _ := template.ParseFiles("templates/index.html")
tmpl.Execute(w, nil)
}</p><p>func calculateHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "只支持POST请求", http.StatusMethodNotAllowed)
return
}</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">r.ParseForm()
aStr := r.FormValue("a")
bStr := r.FormValue("b")
op := r.FormValue("op")
a, err1 := strconv.ParseFloat(aStr, 64)
b, err2 := strconv.ParseFloat(bStr, 64)
if err1 != nil || err2 != nil {
http.Error(w, "请输入有效数字", http.StatusBadRequest)
return
}
var result float64
switch op {
case "+":
result = a + b
case "-":
result = a - b
case "*":
result = a * b
case "/":
if b == 0 {
http.Error(w, "除数不能为零", http.StatusBadRequest)
return
}
result = a / b
default:
http.Error(w, "不支持的操作符", http.StatusBadRequest)
return
}
// 返回结果(可返回JSON或直接渲染页面)
tmpl, _ := template.ParseFiles("templates/index.html")
tmpl.Execute(w, Result{Value: strconv.FormatFloat(result, 'f', -1, 64)})}
func main() { http.HandleFunc("/", indexHandler) http.HandleFunc("/calculate", calculateHandler)
log.Println("服务器启动在 http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))}
使用简单的HTML表单提交数据,支持加减乘除操作。
<!DOCTYPE html>
<html>
<head>
<title>在线计算器</title>
</head>
<body>
<h2>Go语言在线计算器</h2>
<form method="post" action="/calculate">
<input type="text" name="a" placeholder="输入第一个数" required>
<select name="op">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" name="b" placeholder="输入第二个数" required>
<button type="submit">计算</button>
</form>
<p>{{if .Value}}
<h3>结果:<strong>{{.Value}}</strong></h3>
{{end}}
</body>
</html>
确保目录结构正确:
在终端执行:
go run main.go
打开浏览器访问 http://localhost:8080 即可使用计算器。
基本上就这些。功能可以后续扩展,比如支持表达式解析、增加JS动态计算、返回JSON接口供前端调用等。但作为初学者项目,这个版本足够简洁实用。
以上就是Golang开发小型在线计算器项目的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号