登录
首页 >  Golang >  Go问答

主函数中设置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学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>