0

0

Golang如何搭建基础的客户管理系统

P粉602998670

P粉602998670

发布时间:2025-11-16 08:47:51

|

935人浏览过

|

来源于php中文网

原创

答案:用Golang搭建客户管理系统需设计清晰结构,实现增删改查。1. 项目分层为main、handlers、models、routes、storage;2. 定义Customer结构体含ID、Name、Email、Phone;3. 内存存储用map加互斥锁并发安全;4. HTTP处理函数实现API逻辑并校验数据;5. 路由映射使用ServeMux配置;6. 主程序启动服务器监听8080端口;7. 可用curl测试接口。后续可扩展数据库与中间件。

golang如何搭建基础的客户管理系统

用Golang搭建一个基础的客户管理系统并不复杂,重点在于设计清晰的结构、使用合适的库,并实现基本的增删改查功能。下面是一个简单但完整的实现思路和代码示例,适合初学者快速上手。

1. 项目结构设计

合理的项目结构有助于后期维护和扩展。建议采用如下目录结构:

customer-system/
├── main.go
├── handlers/
│ └── customer_handler.go
├── models/
│ └── customer.go
├── routes/
│ └── router.go
└── storage/
└── memory_store.go

这种分层方式将路由、业务逻辑、数据模型和存储分离,便于管理。

2. 定义客户数据模型

models/customer.go 中定义客户结构体:

立即学习go语言免费学习笔记(深入)”;

package models

type Customer struct {
    ID    string `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
    Phone string `json:"phone"`
}

使用JSON标签以便API返回时正确序列化。

3. 实现内存存储(简化版)

为了快速验证逻辑,先用内存模拟数据库。创建 storage/memory_store.go

package storage

import "sync"
import "customer-system/models"

var customers = make(map[string]models.Customer)
var mutex = &sync.Mutex{}

func GetCustomers() []models.Customer {
    var result []models.Customer
    for _, c := range customers {
        result = append(result, c)
    }
    return result
}

func GetCustomerByID(id string) (models.Customer, bool) {
    cust, exists := customers[id]
    return cust, exists
}

func CreateCustomer(c models.Customer) {
    mutex.Lock()
    defer mutex.Unlock()
    customers[c.ID] = c
}

func UpdateCustomer(c models.Customer) bool {
    mutex.Lock()
    defer mutex.Unlock()
    if _, exists := customers[c.ID]; !exists {
        return false
    }
    customers[c.ID] = c
    return true
}

func DeleteCustomer(id string) bool {
    mutex.Lock()
    defer mutex.Unlock()
    if _, exists := customers[id]; !exists {
        return false
    }
    delete(customers, id)
    return true
}

使用互斥锁保证并发安全。

乐彼多用户商城系统LBMall(.net)
乐彼多用户商城系统LBMall(.net)

乐彼多用户商城系统,采用ASP.NET分层技术和AJAX技术,运营于高速稳定的微软.NET+MSSQL 2005平台;完全具备搭建超大型网络购物多用户网上商城的整体技术框架和应用层次LBMall 秉承乐彼软件优秀品质,后台人性化设计,管理窗口识别客户端分辨率自动调整,独立配置的菜单操作锁,使管理操作简单便捷。待办事项1、新订单、支付、付款、短信提醒2、每5分钟自动读取3、新事项声音提醒 店铺管理1

下载

4. 编写API处理函数

handlers/customer_handler.go 中实现HTTP接口逻辑:

package handlers

import (
    "encoding/json"
    "net/http"
    "customer-system/models"
    "customer-system/storage"
)

func GetCustomers(w http.ResponseWriter, r *http.Request) {
    customers := storage.GetCustomers()
    json.NewEncoder(w).Encode(customers)
}

func GetCustomer(w http.ResponseWriter, r *http.Request) {
    id := r.URL.Path[len("/api/customers/"):]

    if cust, exists := storage.GetCustomerByID(id); exists {
        json.NewEncoder(w).Encode(cust)
    } else {
        http.Error(w, "Customer not found", http.StatusNotFound)
    }
}

func CreateCustomer(w http.ResponseWriter, r *http.Request) {
    var cust models.Customer
    if err := json.NewDecoder(r.Body).Decode(&cust); err != nil {
        http.Error(w, "Invalid request body", http.StatusBadRequest)
        return
    }

    if cust.ID == "" || cust.Name == "" || cust.Email == "" {
        http.Error(w, "Missing required fields", http.StatusBadRequest)
        return
    }

    storage.CreateCustomer(cust)
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(cust)
}

func UpdateCustomer(w http.ResponseWriter, r *http.Request) {
    id := r.URL.Path[len("/api/customers/"):]

    var cust models.Customer
    if err := json.NewDecoder(r.Body).Decode(&cust); err != nil || cust.ID != id {
        http.Error(w, "Invalid request body or ID mismatch", http.StatusBadRequest)
        return
    }

    if !storage.UpdateCustomer(cust) {
        http.Error(w, "Customer not found", http.StatusNotFound)
        return
    }

    json.NewEncoder(w).Encode(cust)
}

func DeleteCustomer(w http.ResponseWriter, r *http.Request) {
    id := r.URL.Path[len("/api/customers/"):]

    if !storage.DeleteCustomer(id) {
        http.Error(w, "Customer not found", http.StatusNotFound)
        return
    }

    w.WriteHeader(http.StatusNoContent)
}

5. 配置路由

routes/router.go 中设置路由映射:

package routes

import (
    "net/http"
    "customer-system/handlers"
)

func SetupRouter() *http.ServeMux {
    mux := http.NewServeMux()

    mux.HandleFunc("GET /api/customers", handlers.GetCustomers)
    mux.HandleFunc("GET /api/customers/", handlers.GetCustomer)
    mux.HandleFunc("POST /api/customers", handlers.CreateCustomer)
    mux.HandleFunc("PUT /api/customers/", handlers.UpdateCustomer)
    mux.HandleFunc("DELETE /api/customers/", handlers.DeleteCustomer)

    return mux
}

6. 主程序启动服务

main.go 中启动HTTP服务器:

package main

import (
    "log"
    "net/http"
    "customer-system/routes"
)

func main() {
    router := routes.SetupRouter()

    log.Println("Server starting on :8080")
    log.Fatal(http.ListenAndServe(":8080", router))
}

运行 go run . 即可启动服务。

7. 测试接口示例

使用curl测试创建客户:

curl -X POST http://localhost:8080/api/customers \
  -H "Content-Type: application/json" \
  -d '{"id":"c001","name":"张三","email":"zhangsan@example.com","phone":"13800138000"}'

获取所有客户:
curl http://localhost:8080/api/customers

基本上就这些。这个系统虽然简单,但具备了客户管理的核心功能。后续可以替换内存存储为SQLite或PostgreSQL,加入中间件做日志和验证,使用GORM简化数据库操作,也能接入前端页面。关键是先把流程跑通,再逐步迭代增强。

相关专题

更多
golang如何定义变量
golang如何定义变量

golang定义变量的方法:1、声明变量并赋予初始值“var age int =值”;2、声明变量但不赋初始值“var age int”;3、使用短变量声明“age :=值”等等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

174

2024.02.23

golang有哪些数据转换方法
golang有哪些数据转换方法

golang数据转换方法:1、类型转换操作符;2、类型断言;3、字符串和数字之间的转换;4、JSON序列化和反序列化;5、使用标准库进行数据转换;6、使用第三方库进行数据转换;7、自定义数据转换函数。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

225

2024.02.23

golang常用库有哪些
golang常用库有哪些

golang常用库有:1、标准库;2、字符串处理库;3、网络库;4、加密库;5、压缩库;6、xml和json解析库;7、日期和时间库;8、数据库操作库;9、文件操作库;10、图像处理库。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

335

2024.02.23

golang和python的区别是什么
golang和python的区别是什么

golang和python的区别是:1、golang是一种编译型语言,而python是一种解释型语言;2、golang天生支持并发编程,而python对并发与并行的支持相对较弱等等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

206

2024.03.05

golang是免费的吗
golang是免费的吗

golang是免费的。golang是google开发的一种静态强类型、编译型、并发型,并具有垃圾回收功能的开源编程语言,采用bsd开源协议。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

388

2024.05.21

golang结构体相关大全
golang结构体相关大全

本专题整合了golang结构体相关大全,想了解更多内容,请阅读专题下面的文章。

194

2025.06.09

golang相关判断方法
golang相关判断方法

本专题整合了golang相关判断方法,想了解更详细的相关内容,请阅读下面的文章。

189

2025.06.10

golang数组使用方法
golang数组使用方法

本专题整合了golang数组用法,想了解更多的相关内容,请阅读专题下面的文章。

191

2025.06.17

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

74

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
WEB前端教程【HTML5+CSS3+JS】
WEB前端教程【HTML5+CSS3+JS】

共101课时 | 8.1万人学习

JS进阶与BootStrap学习
JS进阶与BootStrap学习

共39课时 | 3.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号