最新要闻
- 世界观热点:6月20日 11:03分 迈普医学(301033)股价快速拉升
- 日系还香吗?新一代本田皓影混动/插混上市:19.99万起要打比亚迪_世界报资讯
- 16.5亿打造!《封神三部曲》第一部7月20上映:预告片发布
- 全脂/低脂可选:特仑苏纯牛奶2.7元/盒大促(商超6元)
- 世界快看点丨微软明确不会涉足VR:市场实在太小
- 红魔8S Pro首发高频版骁龙8 Gen2!170万跑分比骁龙8 Gen3还猛 焦点速讯
- 【全球新要闻】对在建工程“全面体检”
- 最资讯丨失乐园电影迅雷下载 失乐园电影未删减版迅雷下载
- 债市相对更强,股市估值处相对低位-焦点速递
- 墓地无人汽车探测到“鬼影”!真相到底是什么?
- 上海双层敞篷观光巴士将永久退役:已达13年强制报废标准 后继无车
- 首创双枪充电遥遥领先!比亚迪腾势N7首批量产车下线
- 高考过后 多所知名大学校长纷纷出镜招生|全球短讯
- 新买不到一个月特斯拉充电冒烟爆炸 女车主:很失望 产生心理阴影_天天动态
- 世界观点:菲律宾多方人士反对日本强推核污染水排海:不要污染我们的海洋
- “泰坦尼克”号残骸观光潜艇氧气仅剩96小时 美加部署飞机搜寻
广告
手机
iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?
警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案
- iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?
- 警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案
- 男子被关545天申国赔:获赔18万多 驳回精神抚慰金
- 3天内26名本土感染者,辽宁确诊人数已超安徽
- 广西柳州一男子因纠纷杀害三人后自首
- 洱海坠机4名机组人员被批准为烈士 数千干部群众悼念
家电
A Practical Methodology, HSM, Handler,Service,Model, for Golang Backend Development
(资料图片)
Everybody is familiar with the widely adopted MVC (Model-View-Controller) pattern, which has been used for many years across various languages and frameworks. MVC has proven to be a practical pattern for organizing programs with user interfaces and multiple object models.In this article, I would like to introduce a simple methodology or design pattern called HSM (Handler, Service, Model) or Golang backend development. HSM is similar to MVC but specifically tailored for pure backend development in the Go programming language (Golang).The HSM pattern provides a clear and organized structure for developing backend applications using Golang. Let"s explore its three key components:In a nutshellHandler
The Handler component in HSM serves as the entry point for incoming requests. It handles the routing and request/response handling. Handlers are responsible for receiving requests from clients and orchestrating the flow of data between the service layer and the external world. They act as a bridge between the client and the underlying application logic. For example, HTTP, gRPC, WebSocket, JSONRPC, XMLRPC, TCP, UDP etc.Service
The Service component encapsulates the business logic of the application. It handles the processed input, translated from the handlers. Services are responsible for executing complex operations, interacting with databases or external APIs, and implementing the core functionality of the application. They are designed to be modular and reusable, promoting code maintainability and separation of concerns.Model
The Model component represents the data structures and domain-specific entities used in the application. It includes the data access layer responsible for interacting with databases or other persistent storage. Models in HSM are designed to represent the application"s data schema and provide methods for data retrieval, manipulation, and storage.By adopting the HSM pattern in Golang backend development, you can achieve several benefits:- Improved organization: HSM provides a clear separation of concerns, making it easier to understand and maintain the codebase. Each component has a distinct responsibility, making the codebase more modular and scalable.
- Testability: With the separation of concerns, each component can be tested independently, enabling comprehensive testing of the application"s functionality. Mocking and stubbing can be utilized effectively to isolate components during testing.
- Code reusability: The modular design of HSM allows for the reuse of components across different parts of the application. Handlers, services, and models can be shared and composed to build new features or extend existing functionality, reducing duplication of code and promoting code reuse.
- Flexibility: The HSM pattern provides flexibility in terms of adapting to changing requirements. As the application evolves, components can be modified or added without affecting the entire codebase, making it easier to accommodate new features or adjust the existing behavior.
- Separation of protocol-related request and response from the business logic.
- Processing of business logic involving multiple object models.
- Returning a response based on the data or error from the previous steps.
- Translating the HTTP request into one or multiple inputs for services.
- Invoking one or multiple services to generate output and handle any errors.
- Processing the service output along with errors and returning an appropriate HTTP response.
type Book struct {gorm.ModelName string}type BookLike struct {gorm.ModelBookID uint}Create the Golang service.
type CreateBookInput struct { Name string Like bool}type CreateBookOutput struct { ID uint `json:"id"`}type ServiceInterface interface { CreateBook(context.Context, *CreateBookInput) (*CreateBookOutput, error)}type Service struct { DB *gorm.DB}func (s *Service) CreateBook(ctx context.Context, in *CreateBookInput) (*CreateBookOutput, error) { book := Book{ Name: in.Name, } err := s.DB.Transaction(func(tx *gorm.DB) error { err := tx.Create(&book).Error if err != nil { return err } if in.Like { err = tx.Create(&BookLike{BookID: book.ID}).Error if err != nil { return err } } return nil }) if err != nil { return nil, err } return &CreateBookOutput{ ID: book.ID, }, nil}As we can observe, the service related to books, specifically the
CreateBook
method, handles interactions with both object models. However, it focuses solely on receiving input and generating an output with an error.After implementing the necessary service methods, we are now ready to invoke them from the HTTP handler.type CreateBookRequest struct { Name string `json:"name"` Like bool `json:"like"`}type CreateBookResponse struct { ID uint `json:"id"`}type Server struct { Service ServiceInterface}func (s *Server) CreateBookHandler(w http.ResponseWriter, r *http.Request) { // Parse request. var req CreateBookRequest err := json.NewDecoder(r.Body).Decode(&req) if err != nil { w.WriteHeader(http.StatusBadRequest) return } // Call service with input and output. out, err := s.Service.CreateBook(r.Context(), &CreateBookInput{ Name: req.Name, Like: req.Like, }) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } // Create response from output from last step. res := CreateBookResponse{ ID: out.ID, } // Write response. resJSON, _ := json.Marshal(&res) w.Write(resJSON)}// Create the server with service.func main() { // Open GORM database. db, _ := gorm.Open() // Create service with all clients it needs. svc := Service{DB: db} // Create the HTTP handler and serve it. srv := Server{Service: &svc} http.ListenAndServe(":8080", srv)}This is a typical HTTP handler responsible for handling requests and generating responses. The structure of the HTTP request and response can be automatically generated using tools like oapi-gen or OpenAPI generator, based on your preferences.Now, let"s consider the deployment of this book service as a microservice on AWS Lambda. The resulting program would look like the following:
var svc ServiceInterfacetype CreateBookEvent struct { Name string `json:"name"`}func HandleLambdaRequest(ctx context.Context, evt CreateBookEvent) (string, error) { out, err := svc.CreateBook(ctx, &CreateBookInput{ Name: evt.Name, }) if err != nil { return "", err } outJSON, err := json.Marshal(out) return string(outJSON), err}func main() { db, _ := gorm.Open() svc = &Service{DB: db} lambda.Start(HandleLambdaRequest)}Nearly the same right.By organizing all the business logic into a concept called "service," we can easily encapsulate complex logic without coupling it to any specific protocol. This means that the book service we have developed can be fully reused. By adding the necessary glue code for a specific protocol or framework, the new program can be deployed instantly without altering the underlying logic. The service can also contain interfaces to other services, and the handler structure can include a list of services for cohesive functionality.Now, let"s consider another common pattern found in web development. However, most of these patterns fail to address a fundamental problem: how to efficiently handle complex business logic that involves multiple object models and write reusable code.The straightforward solution to this challenge is the repository-based pattern, which is inspired by the classical Java DAO (Data Access Object) pattern. When dealing with numerous object models or when the program is in its early stages, writing and constantly changing duplicated interfaces can become time-consuming. The repository pattern aims to centralize single model access logic, not many or complicated.However, in practice, bugs tend to reside within the business logic code rather than in the repository or database IO. Furthermore, repositories can be overly simplistic, and writing unit tests for them may be unnecessary at the early stages of development.The more complex the repository code becomes, the more effort is required to access the objects themselves. In the context of the program, accessing object models is often the most critical part of the business logic. When objects are retrieved from the database, the actual computation begins immediately, and the results are written back to the database. As SQL queries become more intricate, or when multiple object models need to be handled within a transaction, or when database access optimization is necessary, the repository pattern can become a bottleneck within the program. This often leads to the repository classes being replaced by direct object access, which is where the HSM pattern comes into play.This article aims to provide valuable insights for your Golang backend development by introducing the HSM pattern as a solution to the challenges of handling complex business logic efficiently.
关键词:
-
A Practical Methodology, HSM, Handler,Service,Model, for Golang Backend Developm
AsimplemethodologyordesignpatterncalledHSM(Handler,Service,Model)o
来源: A Practical Methodology, HSM, Handler,Service,Model, for Golang Backend Developm
【环球聚看点】直播源码搭建技术弹幕消息功能的实现
世界观热点:6月20日 11:03分 迈普医学(301033)股价快速拉升
日系还香吗?新一代本田皓影混动/插混上市:19.99万起要打比亚迪_世界报资讯
16.5亿打造!《封神三部曲》第一部7月20上映:预告片发布
全脂/低脂可选:特仑苏纯牛奶2.7元/盒大促(商超6元)
世界快看点丨微软明确不会涉足VR:市场实在太小
红魔8S Pro首发高频版骁龙8 Gen2!170万跑分比骁龙8 Gen3还猛 焦点速讯
【全球新要闻】对在建工程“全面体检”
全球新资讯:关于线性结构中的双向链表如何实现?
NCalc 学习笔记 (六)|天天观热点
也说一说IDEA热部署Web项目最终解决方案,确实大大提高工作效率
每日视点!详解在 Linux 启动时,如何自动执行命令或脚本
最资讯丨失乐园电影迅雷下载 失乐园电影未删减版迅雷下载
债市相对更强,股市估值处相对低位-焦点速递
墓地无人汽车探测到“鬼影”!真相到底是什么?
上海双层敞篷观光巴士将永久退役:已达13年强制报废标准 后继无车
首创双枪充电遥遥领先!比亚迪腾势N7首批量产车下线
高考过后 多所知名大学校长纷纷出镜招生|全球短讯
新买不到一个月特斯拉充电冒烟爆炸 女车主:很失望 产生心理阴影_天天动态
世界观点:菲律宾多方人士反对日本强推核污染水排海:不要污染我们的海洋
springboot~http请求头中如何放中文 当前快报
“泰坦尼克”号残骸观光潜艇氧气仅剩96小时 美加部署飞机搜寻
“全球第一吊”挑战191米最大陆上风力发电机 仅17分钟升至40层楼高
每日短讯:男子长城藏时间胶囊12年多人留纸条 网友直呼奇妙交流:很浪漫
屏摄电影被男子怒斥 影院称屏摄会对胶片有损伤 网友质疑:侮辱智商?-速讯
每日热门:美系开卷国产电动车!别克中大型轿跑E4上市:18.99万起
今日阵雨叨扰,周三周四阳光又将登场,抓紧洗晒! 环球热消息
【读财报】券商资管基金透视:财通、国泰君安资管年内收益领跑 中银证券业绩垫底 视讯
水电大省遭遇“水荒” 四川云南5月水电仍在下降
全球首例!杭州医生用5G帮5000公里外的新疆病人切除肝脏 画面网友惊叹
海口一特斯拉撞飞小车致一死一伤 现场视频被撞车360度旋转、有孩子被甩出-天天时快讯
电瓶车室内充电爆炸 墙都裂了 轮椅老人被吓得拔腿就跑 全球时讯
自救失败!“海航系”公司退市…
读发布!设计与部署稳定的分布式系统(第2版)笔记06_用户_世界观焦点
信息:手机可拆卸电池即将回归:利大于弊 别再被苹果牵着走
环球热资讯!回忆杀!高圆圆晒与贾静雯私照 梦回《倚天屠龙记》周芷若和赵敏
今日看点:早泄能治好吗?
100个物联网项目(基于ESP32)2快速入门
【linux命令】“瑞士军刀”nc的用法简介-天天关注
STL
马云指出淘宝天猫未来三个方向:回归淘宝、回归用户、回归互联网
花了1330万 还有600万只:巴黎向老鼠投降了 要“同居”_全球热点
冷清的618 焦虑的手机厂商:未来只能靠苹果创新了?
跳桥救人小哥引来女网友公开示爱:网友警告切勿炒作 世界热点评
中国男足亚运队1-0胜韩国U24队:孙沁涵抽射建功
美国能单挑全世界吗(美国军力全球第一敢于与世界敌么)
观焦点:登陆百度网盘错误 1550017 百度云同步盘登录失败155010
趋之若鹜的鹜什么意思_趋之若鹜
《王者荣耀》发布S32赛季漂泊之剑预告PV 两款战令皮肤奖励公布
韩国首尔教育厅将对学校供餐用水产品进行全面辐射检测 旨在保证食品安全
微信上线“安静模式” 专为有听力障碍的人创造更好的环境
《庆余年2》公布喜相逢版角色海报 增加一些重要新人物
JUC同步锁原理源码解析五----Phaser 今日热搜
ASP.NET Core MVC 从入门到精通之日志管理_世界热闻
计算几何之两条线段的交点|世界时快讯
看点:博客项目01
“狗狗嫌天热自己坐电梯回家”登上热搜 主人急里忙慌寻找
炒菜用什么油好?
车企卖衣服 不务正业? 焦点信息
微软Win11处理器要求变动:AMD、英特尔一大波新U加入支持
InnoDB 缓冲池
天天资讯:俄罗斯天然气工业银行拟参与无担保人民币债券市场
做小吃前途如何?惠记粉汤羊血加盟开店,开哪儿都火!
天天短讯!特斯拉车祸后复出 演员林志颖首次现身内地商演
专家称年轻人撑不起车市:中老年人才有足够能力拉动市场|视讯
今日精选:予以的拼音(予以)
【财经分析】数据赋能城市升级——2023中国资源型老工业城市转型发展指数研讨会在北京举办
每天喝咖啡的人 20年后都怎么样了?三大好处、三大不要 焦点精选
2024年见 龙芯也要做显卡了:IP设计已完成 还在优化
冷知识!大熊猫近视高达800度:只能看清几米之内物体 看热讯
索尼粉丝迷惑行为:请愿Xbox第一方游戏《星空》成PS5独占
开票!2023年安阳首场演唱会等你来抢!附购票入口
Liunx nginx服务|环球要闻
Manacher算法学习笔记
世界最新:799元价格屠夫!小米电视把国外品牌全打趴了
外来生物美国珍珠鳖被放生太湖:围观者欢呼雀跃|世界简讯
天天热讯:Mate发布Voicebox AI模型:仅需2秒片段即可“学会”语音细节
全球热资讯!首发4899元 外星人新款27英寸游戏显示器上架:180Hz高刷
国产操作系统赶超Win 10 统信UOS更新:换机可批量重装软件
世界头条:因编造、传播与期货交易有关的虚假信息行为 上海点钢电子商务被罚30万元
【环球热闻】Rust语言 - 接口设计的建议之显而易见(Obvious)
天猫品牌评估一般几天_天猫品牌评估_最新消息
北京电动自行车新规今起实施:电池温度达80度需有报警音
世界新消息丨女孩毕业典礼捐10万:含4年奖学金 用于帮助乡村孩子
当前观点:高通、联发科找到共同点了:骁龙8G3、天玑9300 AI性能爆发
云南普者黑现罕见的粉白相间荷花:花瓣如脂如玉 世界快播报
ppt讲课技巧互动_ppt讲课技巧 世界视点
【解决方法】锐捷 EVE 模拟器关联 Wireshark 进行抓包 焦点速讯
js-audio-recorder 插件实现web端录音
曼努埃尔·加西亚(关于曼努埃尔·加西亚介绍)
新加坡一廉价航班飞机降落后发现少个轮胎:曾出现胎压异常
全球领先!刘经南院士:北斗是唯一集通导遥等功能卫星导航系统 新视野
民营卫星俯拍四川盆地:中国两项唯一的天府之国 全球焦点
世界关注:达标没?调查称53.7%年轻人存款不足10万 感受下中等收入群体收入标准
海口一特斯拉高速行驶撞飞小车 官方通报:致一死一伤_当前独家
英雄联盟更新不动了怎么办_英雄联盟更新不动
【解决办法】DHCP Relay环境中PC无法获取IP地址,排错与解法 全球新要闻
华为云邓明昆:云原生时代,以开源赋能数字化转型
每日视讯:Quartz.net的最佳实践