登录
首页 >  Golang >  Go问答

如何在 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删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>