【Go语言实战】(2) Gin+Vue 电子商城

简介: 目录🎈1. 需求分析1.1 数据获取1.2 ⽤户操作1.3 其他功能1.4 拓展功能1.5 开发环境🎉2. 后端逻辑代码2.1 Python - 爬虫2.2 Golang - Gin2.2.1 数据库部分2.2.1 服务部分✨3. 前端核心代码3.1 AXIOS前后端交互🎊4. 部分页面展示4.1 前台页面4.2 后台管理🎆5. 结语🎇最后

目录

🎈1. 需求分析

1.1 数据获取

1.2 ⽤户操作

1.3 其他功能

1.4 拓展功能

1.5 开发环境

🎉2. 后端逻辑代码

2.1 Python - 爬虫

2.2 Golang - Gin

2.2.1 数据库部分

2.2.1 服务部分

✨3. 前端核心代码

3.1 AXIOS前后端交互

🎊4. 部分页面展示

4.1 前台页面

4.2 后台管理

🎆5. 结语

🎇最后



🎈1. 需求分析

1.1 数据获取

使⽤爬⾍爬取某⼀电商平台上部分商品信息,包括但不限于商品图⽚、价格、名称等。


1.2 ⽤户操作

顾客


注册,登录,登出

⽤户个⼈资料展示与编辑,上传头像

更改密码

商家


拥有顾客的⼀切功能

可以进⾏零⻝信息的上传(包括图⽚、价格等信息)

管理员


拥有上述⽤户的所有功能

⽤户管理

商品信息管理

1.3 其他功能

添加虚拟货币功能。

订单有过期时间

为管理员添加⼀个充值接⼝,管理员可以为某⼀⽤户加钱。

添加购物⻋和背包功能。 购买操作在购物⻋界⾯完成,完成购买后完成物品转移,以及货币转移(购买后物品⾃动下架)

背包中的物品可以由⽤户上传,但默认不在购物⻚⾯中出现,需持有者进⾏上架才能被其他⽤户购买。

1.4 拓展功能

⽀付密码

商品下评论

注意并发性

1.5 开发环境

后端:Python v3.8 、Golang v1.15


数据库:MySql v5.7.30、Redis v4.0.9


文件存储 :七牛云存储


支付接口:支付FM


🎉2. 后端逻辑代码

2.1 Python - 爬虫

数据库表

class product_img_info(Base):
    __tablename__ = 'product_param_img'  # 数据库中的表名
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(), nullable=False)
    title = Column(String())
    category_id = Column(String())
    product_id = Column(String())
    info = Column(String())
    img_path = Column(String())
    price = Column(String())
    discount_price = Column(String())
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now)
    deleted_at = Column(DateTime, default = None)
    def __repr__(self):
        return """
            <product_img_info(id:%s, product_id:%s>
        """ % (self.id,self.product_id)

爬取操作

def getHTMLText(url):
    try:
        header = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36',
            'cookie': '' # 到浏览器复制cookie
        }
        r = requests.get(url, timeout=30, headers=header)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        # print(r.text)
        return r.text
    except:
        return ""
def parsePage(html):
    view_prices = re.findall(r'\"view_price\"\:\"[\d\.]*\"', html)
    view_fees = re.findall(r'\"view_fee\"\:\"[\d\.]*\"', html)
    raw_titles = re.findall(r'\"raw_title\"\:\".*?\"', html)
    titles = re.findall(r'\"title\"\:\".*?\"', html)
    user_ids = re.findall(r'\"user_id\"\:\"[\d\.]*\"',html)
    pic_urls = re.findall(r'\"pic_url\"\:\".*?\"',html)
    detail_urls = re.findall(r'\"detail_url\"\:\".*?\"',html)
    for view_price,view_fee,title,raw_title,user_id,pic_url,detail_url in zip(view_prices,view_fees,titles,raw_titles,user_ids,pic_urls,detail_urls):
        price=eval(view_price.split(':')[1])
        discount_price=eval(view_fee.split(':')[1])
        name=eval(title.split(':')[1])
        a4=eval(raw_title.split(':')[1])
        product_id=eval(user_id.split(':')[1])
        img_path=eval(pic_url.split(':')[1])
        persopn = product_img_info(name=name,title=name,product_id=product_id,category_id="6",info=name,img_path=img_path,price=price,discount_price=discount_price)
        session.add(persopn)  # 增加一个
        session.commit() # 提交到数据库中
# 1手机 2女装 3电脑 4杯子 5零食 6耳机
def main():
    goods = '耳机'
    depth = 1
    start_url = 'https://s.taobao.com/search?q=' + goods
    for i in range(depth):
        try:
            url = start_url + '&s=' + str(44 * i)
            html = getHTMLText(url)
            parsePage(html)
        except:
            continue
if __name__ == '__main__':
   # Base.metadata.create_all()       # 创建表需要执行这行代码,如果表存在则不创建
    #sqlOperation()
    main()

2.2 Golang - Gin

2.2.1 数据库部分

部分数据库建设


用户模型

//User 用户模型
type User struct {
  gorm.Model
  UserName       string `gorm:"unique"`
  Email          string //`gorm:"unique"`
  PasswordDigest string
  Nickname       string `gorm:"unique"`
  Status         string
  Limit          int   // 0 非管理员  1 管理员
  Type           int    // 0表示用户  1表示商家
  Avatar         string `gorm:"size:1000"`
  Monery       int
}

商品模型

//商品模型
type Product struct {
  gorm.Model
  ProductID     string `gorm:"primary_key"`
  Name          string
  CategoryID    int
  Title         string
  Info          string `gorm:"size:1000"`
  ImgPath       string
  Price         string
  DiscountPrice string
  OnSale     string
  Num     int
  BossID        int
  BossName      string
  BossAvatar    string
}

2.2.1 服务部分

部分逻辑代码


增加商品

func (service *UpProductService) UpProduct() serializer.Response {
  var product model.Product
  code := e.SUCCESS
  err := model.DB.First(&product,service.ID).Error
  if err != nil {
  logging.Info(err)
  code = e.ErrorDatabase
  return serializer.Response{
    Status: code,
    Msg:    e.GetMsg(code),
    Error:  err.Error(),
  }
  }
  product.OnSale = service.OnSale
  err = model.DB.Save(&product).Error
  if err != nil {
  logging.Info(err)
  code = e.ErrorDatabase
  return serializer.Response{
    Status: code,
    Msg:    e.GetMsg(code),
    Error:  err.Error(),
  }
  }
  return serializer.Response{
  Status: code,
  Data:   serializer.BuildProduct(product),
  Msg:    e.GetMsg(code),
  }
}

修改商品

//更新商品
func (service *UpdateProductService) Update() serializer.Response {
  product := model.Product{
  Name:          service.Name,
  CategoryID:    service.CategoryID,
  Title:         service.Title,
  Info:          service.Info,
  ImgPath:       service.ImgPath,
  Price:         service.Price,
  DiscountPrice: service.DiscountPrice,
  OnSale:     service.OnSale,
  }
  product.ID = service.ID
  code := e.SUCCESS
  err := model.DB.Save(&product).Error
  if err != nil {
  logging.Info(err)
  code = e.ErrorDatabase
  return serializer.Response{
    Status: code,
    Msg:    e.GetMsg(code),
    Error:  err.Error(),
  }
  }
  return serializer.Response{
  Status: code,
  Msg:    e.GetMsg(code),
  }
}

✨3. 前端核心代码

3.1 AXIOS前后端交互
import axios from 'axios'
// 创建商品
const postProduct = form =>
    axios.post('/api/v1/products', form).then(res => res.data)
// 读商品详情
const showProduct = id =>
    axios.get(`/api/v1/products/${id}`).then(res => res.data)
// 读取商品列表
const listProducts = (category_id, start, limit) =>
  axios
    .get('/api/v1/products', { params: { category_id, start, limit } })
    .then(res => res.data)
//读取商品的图片
const showPictures = id => axios.get(`/api/v1/imgs/${id}`).then(res => res.data)
//搜索商品
const searchProducts = form =>
    axios.post('/api/v1/searches', form).then(res => res.data)
export {
    postProduct,
    showProduct,
    listProducts,
    showPictures,
    searchProducts
}

🎊4. 部分页面展示

4.1 前台页面

主页面

image.pngimage.png

商品页面


image.png


image.png

发布商品

image.png


购物车

image.png


结算页面

image.png


个人中心

image.png


4.2 后台管理

用户管理

image.png

商品管理

image.png


🎆5. 结语

这个商场是在作者的开源项目基础上加以改进的!

原GitHub地址:CongZ666

真的非常感谢作者的开源

让我能通过这个项目,懂得Gin+Vue前后端分离的很多知识!!

还有懂了一些如同支付功能等,之前没有做过的功能。

不过我还没搞懂极验的功能。后续再完善。


🎇最后

小生凡一,期待你的关注。





相关文章
|
3月前
|
Linux Go iOS开发
Go语言100个实战案例-进阶与部署篇:使用Go打包生成可执行文件
本文详解Go语言打包与跨平台编译技巧,涵盖`go build`命令、多平台构建、二进制优化及资源嵌入(embed),助你将项目编译为无依赖的独立可执行文件,轻松实现高效分发与部署。
|
3月前
|
消息中间件 缓存 NoSQL
Redis各类数据结构详细介绍及其在Go语言Gin框架下实践应用
这只是利用Go语言和Gin框架与Redis交互最基础部分展示;根据具体业务需求可能需要更复杂查询、事务处理或订阅发布功能实现更多高级特性应用场景。
289 86
|
4月前
|
数据采集 数据挖掘 测试技术
Go与Python爬虫实战对比:从开发效率到性能瓶颈的深度解析
本文对比了Python与Go在爬虫开发中的特点。Python凭借Scrapy等框架在开发效率和易用性上占优,适合快速开发与中小型项目;而Go凭借高并发和高性能优势,适用于大规模、长期运行的爬虫服务。文章通过代码示例和性能测试,分析了两者在并发能力、错误处理、部署维护等方面的差异,并探讨了未来融合发展的趋势。
335 0
|
4月前
|
存储 人工智能 Go
Go-Zero全流程实战即时通讯
Go-Zero 是一个功能丰富的微服务框架,适用于开发高性能的即时通讯应用。它具备中间件、工具库和代码生成器,简化开发流程。本文介绍其环境搭建、项目初始化及即时通讯功能实现,涵盖用户认证、消息收发和实时推送,帮助开发者快速上手。
312 0
|
3月前
|
监控 前端开发 数据可视化
Github 12.3kstar, 3分钟起步做中后台?Go+Vue 脚手架,把权限、代码生成、RBAC 都封装好了
Go-admin 是基于 Gin + Vue 的中后台脚手架,集成 Casbin RBAC 权限、JWT 鉴权、GORM 数据库操作与 Swagger 文档,内置用户、角色、菜单等管理模块。提供代码生成器与表单构建器,支持多租户与多前端框架(Element UI/Arco/Ant Design),3 分钟快速搭建企业级后台,助力高效交付。
239 4
|
3月前
|
存储 前端开发 JavaScript
Go语言实战案例-项目实战篇:编写一个轻量级在线聊天室
本文介绍如何用Go语言从零实现一个轻量级在线聊天室,基于WebSocket实现实时通信,支持多人消息广播。涵盖前后端开发、技术选型与功能扩展,助你掌握Go高并发与实时通信核心技术。
|
4月前
|
负载均衡 监控 Java
微服务稳定性三板斧:熔断、限流与负载均衡全面解析(附 Hystrix-Go 实战代码)
在微服务架构中,高可用与稳定性至关重要。本文详解熔断、限流与负载均衡三大关键技术,结合API网关与Hystrix-Go实战,帮助构建健壮、弹性的微服务系统。
490 1
微服务稳定性三板斧:熔断、限流与负载均衡全面解析(附 Hystrix-Go 实战代码)
|
4月前
|
安全 Go 开发者
Go语言实战案例:使用sync.Mutex实现资源加锁
在Go语言并发编程中,数据共享可能导致竞态条件,使用 `sync.Mutex` 可以有效避免这一问题。本文详细介绍了互斥锁的基本概念、加锁原理及实战应用,通过构建并发安全的计数器演示了加锁与未加锁的区别,并封装了一个线程安全的计数器结构。同时对比了Go中常见的同步机制,帮助开发者理解何时应使用 `Mutex` 及其注意事项。掌握 `Mutex` 是实现高效、安全并发编程的重要基础。
|
4月前
|
数据采集 Go API
Go语言实战案例:使用context控制协程取消
本文详解 Go 语言中 `context` 包的使用,通过实际案例演示如何利用 `context` 控制协程的生命周期,实现任务取消、超时控制及优雅退出,提升并发程序的稳定性与资源管理能力。
|
4月前
|
数据采集 Go API
Go语言实战案例:多协程并发下载网页内容
本文是《Go语言100个实战案例 · 网络与并发篇》第6篇,讲解如何使用 Goroutine 和 Channel 实现多协程并发抓取网页内容,提升网络请求效率。通过实战掌握高并发编程技巧,构建爬虫、内容聚合器等工具,涵盖 WaitGroup、超时控制、错误处理等核心知识点。

热门文章

最新文章