主函数中设置Mongo客户端,其他模块接收nil值
来源:stackoverflow
时间:2024-03-03 17:51:26 395浏览 收藏
欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《主函数中设置Mongo客户端,其他模块接收nil值》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!
我有一个利用 mux 和 mongo-driver 的宁静 api。按照教程,我尝试在主包中设置服务器和 mongo 客户端:
package main
import (
"context"
"fmt"
"net/http"
"time"
"github.com/gorilla/mux"
c "github.com/moonlightfight/elo-backend/config"
"github.com/moonlightfight/elo-backend/routes/admin"
"github.com/moonlightfight/elo-backend/routes/tournament"
"github.com/spf13/viper"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var client *mongo.client
func main() {
// set the file name of the configurations file
viper.setconfigname("config")
// set the path to look for the configurations file
viper.addconfigpath(".")
// enable viper to read environment variables
viper.automaticenv()
viper.setconfigtype("yml")
var configuration c.configurations
if err := viper.readinconfig(); err != nil {
fmt.printf("error reading config file, %s", err)
}
err := viper.unmarshal(&configuration)
if err != nil {
fmt.printf("unable to decode into struct, %v", err)
}
ctx, _ := context.withtimeout(context.background(), 10*time.second)
clientoptions := options.client().applyuri(fmt.sprintf("mongodb+srv://%s:%[email protected]/%s?retrywrites=true&w=majority", configuration.database.dbuser, configuration.database.dbpass, configuration.database.dbname))
port := fmt.sprintf(":%d", configuration.server.port)
mongo.connect(ctx, clientoptions)
router := mux.newrouter()
router.handlefunc("/api/admin", admin.createadminendpoint).methods("post")
router.handlefunc("/api/admin/login", admin.adminloginendpoint).methods("post")
router.handlefunc("/api/tournament/getfromweb", tournament.gettournamentdata).methods("get")
fmt.printf("server listening on http://localhost%v", port)
http.listenandserve(port, router)
}
现在,为了更简洁地管理我的代码,我设置了模块(如您在 main 的导入中看到的那样)来处理 mux 将用于端点的函数。
在一种特定情况下(处理“/api/admin”端点:
package admin
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
c "github.com/moonlightfight/elo-backend/config"
m "github.com/moonlightfight/elo-backend/models"
"github.com/spf13/viper"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"golang.org/x/crypto/bcrypt"
)
var client *mongo.Client
// other code here
func CreateAdminEndpoint(response http.ResponseWriter, request *http.Request) {
response.Header().Set("content-type", "application/json")
var admin m.Admin
err := json.NewDecoder(request.Body).Decode(&admin)
if err != nil {
log.Println(err)
}
// encrypt user password
admin.Password = HashPassword(admin.Password)
fmt.Println(client)
collection := client.Database("test").Collection("Admin")
ctx, ctxErr := context.WithTimeout(context.Background(), 5*time.Second)
if ctxErr != nil {
log.Println(ctxErr)
}
result, resErr := collection.InsertOne(ctx, admin)
if resErr != nil {
log.Println(resErr)
}
json.NewEncoder(response).Encode(result)
}
运行时,我收到以下错误:
2021/06/05 02:02:39 http: 恐慌服务 [::1]:53359: 运行时错误: 无效的内存地址或 nil 指针取消引用
这指向我在端点函数中定义集合的行,该函数记录为具有 nil 值。我显然没有在模块中正确定义 mongo 客户端,并且不确定跨多个模块维护此客户端连接的最佳实践。
正确答案
在避免全局变量的同时执行此操作的标准方法是定义一个代表服务器的 struct ,其方法将是处理程序。然后这些方法共享结构体的数据,并且您可以将诸如 mongo 客户端之类的东西放在那里。
类似这样的东西(在你的 admin 包中):
type server struct {
client *mongo.client
}
func newserver(client *mongo.client) *server {
return &server{client: client}
}
func (srv *server) createadminendpoint(response http.responsewriter, request *http.request) {
// ...
// use srv.client here
//
}
现在在 main 中,您可以像这样创建服务器:
client, err := mongo.Connect(...)
// handle err!
srv := admin.NewServer(client)
router := mux.NewRouter()
router.HandleFunc("/api/admin", srv.CreateAdminEndpoint).Methods("POST")本篇关于《主函数中设置Mongo客户端,其他模块接收nil值》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习