用Golang开发个人财务管理系统可提升编程能力,项目结构清晰分层,包含model、storage、service和handler,通过JSON文件存储收支数据,使用net/http实现REST API,支持记录收入支出、分类查询,并可扩展数据库、预算提醒、前端展示等功能。

用Golang开发个人财务管理系统是一个实用且能提升编程能力的项目。这类系统可以帮助用户记录收入、支出,分类统计,查看报表,甚至设置预算提醒。下面是一个简洁但功能完整的示例,涵盖核心模块设计、数据结构、基础API和存储方式。
一个清晰的项目结构有助于后期维护和扩展:
├── main.go将业务逻辑分层:model 定义数据结构,storage 负责持久化(如文件或数据库),service 处理业务规则,handler 提供HTTP接口。
定义关键结构体来表示财务数据:
立即学习“go语言免费学习笔记(深入)”;
// internal/model/transaction.go
package model
import "time"
type Transaction struct {
ID int `json:"id"`
Amount float64 `json:"amount"`
Type string `json:"type"` // income 或 expense
Category string `json:"category"` // 如餐饮、工资、交通
Note string `json:"note,omitempty"`
Date time.Time `json:"date"`
}这个结构体可以表示每一笔收支记录,通过Type字段区分收入和支出。
为简化示例,使用本地JSON文件作为持久化存储:
// internal/storage/storage.go
package storage
import (
"encoding/json"
"os"
"sync"
"yourapp/internal/model"
)
type Storage struct {
file string
data []model.Transaction
mu sync.Mutex
}
func NewStorage(file string) (*Storage, error) {
s := &Storage{file: file}
if err := s.load(); err != nil {
return nil, err
}
return s, nil
}
func (s *Storage) load() error {
s.mu.Lock()
defer s.mu.Unlock()
data, err := os.ReadFile(s.file)
if err != nil {
if os.IsNotExist(err) {
s.data = []model.Transaction{}
return nil
}
return err
}
return json.Unmarshal(data, &s.data)
}
func (s *Storage) save() error {
s.mu.Lock()
defer s.mu.Unlock()
data, err := json.MarshalIndent(s.data, "", " ")
if err != nil {
return err
}
return os.WriteFile(s.file, data, 0644)
}
func (s *Storage) Add(tx model.Transaction) error {
tx.ID = len(s.data) + 1
s.data = append(s.data, tx)
return s.save()
}
func (s *Storage) GetAll() []model.Transaction {
s.mu.Lock()
defer s.mu.Unlock()
return s.data
}
func (s *Storage) GetByCategory(category string) []model.Transaction {
s.mu.Lock()
defer s.mu.Unlock()
var result []model.Transaction
for _, t := range s.data {
if t.Category == category {
result = append(result, t)
}
}
return result
}使用 sync.Mutex 避免并发写入问题,数据保存在 transactions.json 文件中。
使用 net/http 实现简单的REST风格API:
// internal/handler/transaction_handler.go
package handler
import (
"encoding/json"
"net/http"
"yourapp/internal/model"
"yourapp/internal/storage"
)
type TransactionHandler struct {
store *storage.Storage
}
func NewTransactionHandler(store *storage.Storage) *TransactionHandler {
return &TransactionHandler{store: store}
}
func (h *TransactionHandler) Create(w http.ResponseWriter, r *http.Request) {
var tx model.Transaction
if err := json.NewDecoder(r.Body).Decode(&tx); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if tx.Type != "income" && tx.Type != "expense" {
http.Error(w, "type must be 'income' or 'expense'", http.StatusBadRequest)
return
}
tx.Date = r.Context().Value("now").(time.Time) // 可注入时间用于测试
if err := h.store.Add(tx); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(tx)
}
func (h *TransactionHandler) List(w http.ResponseWriter, r *http.Request) {
txx := h.store.GetAll()
json.NewEncoder(w).Encode(txx)
}main.go 中启动服务器:
// main.go
package main
import (
"log"
"net/http"
"yourapp/internal/handler"
"yourapp/internal/storage"
)
func main() {
store, err := storage.NewStorage("transactions.json")
if err != nil {
log.Fatal(err)
}
handler := handler.NewTransactionHandler(store)
http.HandleFunc("/transactions", func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), "now", time.Now())
r = r.WithContext(ctx)
switch r.Method {
case http.MethodGet:
handler.List(w, r)
case http.MethodPost:
handler.Create(w, r)
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
})
log.Println("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}运行后可通过 curl 测试:
curl -X POST http://localhost:8080/transactions \ -H "Content-Type: application/json" \ -d '{"amount": 5000, "type": "income", "category": "salary", "note": "本月工资"}'此为基础版本,后续可增加:
基本上就这些。这个示例展示了如何用Golang构建一个轻量级但可扩展的个人财务系统,重点在于结构清晰、职责分离和易于测试。不复杂但容易忽略。
以上就是Golang开发个人财务管理系统示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号