亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Go 中以慣用的方式將數據庫訪問權限轉換為函數

如何在 Go 中以慣用的方式將數據庫訪問權限轉換為函數

Go
POPMUISE 2023-06-05 17:17:16
我在 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 successfunc 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實際的數據庫訪問方法本身。
查看完整描述

1 回答

?
胡子哥哥

TA貢獻1825條經驗 獲得超6個贊

據我了解,連接應該長期存在并設置為構造函數的一部分,即不是請求流的一部分。


這通??雌饋硐襁@樣:


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在那里實現對 in 的調用,但在我看來,只有當您遇到您認為可以通過重新連接恢復的故障時才應嘗試這樣做。


查看完整回答
反對 回復 2023-06-05
  • 1 回答
  • 0 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號