如何在 Go 中将数据库访问变成惯用的函数
来源:stackoverflow
时间:2024-04-05 12:18:30 308浏览 收藏
大家好,我们又见面了啊~本文《如何在 Go 中将数据库访问变成惯用的函数》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~
问题内容
我已经在 go 中构建了一个后端 api,它可以工作,但是我想将数据库访问层的代码重构为一个函数 - 惯用的方式。
// Get the form data entered by client; FirstName, LastName, phone Number, // assign the person a unique i.d // check to see if that user isn't in the database already // if they are send an error message with the a 'bad' response code // if they aren't in db add to db and send a message with success func CreateStudentAccountEndpoint(response http.ResponseWriter, request *http.Request){ client, err := mongo.NewClient("mongodb://localhost:27017") if err != nil { log.Fatalf("Error connecting to mongoDB client Host: Err-> %v\n ", err) } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() err = client.Connect(ctx) if err != nil { log.Fatalf("Error Connecting to MongoDB at context.WtihTimeout: Err-> %v\n ", err) } response.Header().Set("Content-Type", "application/json") studentCollection := client.Database(dbName).Collection("students") _, err = studentCollection.InsertOne(context.Background(),data) if err != nil { response.WriteHeader(501) response.Write([]byte(`{ "message": "` + err.Error() + `" }`)) } // encoding json object for returning to the client jsonStudent, err := json.Marshal(student) if err != nil { http.Error(response, err.Error(), http.StatusInternalServerError) } response.Write(jsonStudent) }
我知道我可以创建一个返回 (*mongoclient, err) 的方法,因为我稍后在代码中使用客户端局部变量。
但是,我不知道如何实现 defer cancel()
部分,因为它会在方法 createstudenaccountendpoint
结束时执行。但我不知道如何在一种方法中实现此 defer
部分,该方法将认识到我希望延迟发生在调用数据库访问层方法的函数末尾,例如 createstudentaccountendpoint
而不是实际的数据库访问方法本身。 /p>
解决方案
据我了解,连接应该是长期存在的,并设置为构造函数的一部分,即不是请求流的一部分。
这通常看起来像这样:
type BackendAPI struct { client *mongo.Client } func NewBackendAPI(mongoURI string) (*BackendAPI, error) { client, err := mongo.NewClient(mongoURI) if err != nil { return nil, err } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() err = client.Connect(ctx) if err != nil { return nil, err } return &BackendAPI{client}, nil } func (api *BackendAPI) func CreateStudentAccountEndpoint(response http.ResponseWriter, request *http.Request) { response.Header().Set("Content-Type", "application/json") // note the use of the long-lived api.client, which is connected already. studentCollection := api.client.Database(dbName).Collection("students") _, err = studentCollection.InsertOne(context.Background() ,data) if err != nil { response.WriteHeader(501) response.Write([]byte(`{ "message": "` + err.Error() + `" }`)) return // at this point, the method should return } // encoding json object for returning to the client jsonStudent, err := json.Marshal(student) if err != nil { http.Error(response, err.Error(), http.StatusInternalServerError) } response.Write(jsonStudent) }
如果您担心失去连接,您可以在那里实现对 api.client.ping
的调用,但在我看来,只有当您遇到您认为可以通过重新连接恢复的故障时才应该尝试这样做。 p>
今天关于《如何在 Go 中将数据库访问变成惯用的函数》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
最新阅读
更多>
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习