0

我在 Go 中构建了一个后端 API,它可以工作,但是我想将 DB 访问层的代码重构为一个函数 - 惯用。

// 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在一种方法中实现本节,该方法将认识到我希望延迟发生在调用 DB 访问层方法的函数的末尾,例如CreateStudentAccountEndpoint,而不是实际的 db 访问方法本身。

4

1 回答 1

1

As I understand it, the connection should be long-lived and set up as a part of a constructor, i.e. not part of the request flow.

This will typically look something like this:

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)
}

If you worry about losing the connection, you could implement a call to api.client.Ping in there, but in my opinion this should only be attempted if you encounter a failure you believe you can recover from by reconnecting.

于 2019-02-05T08:07:20.000 回答