doujia1871 2019-02-05 07:37
浏览 28

如何在Go中惯用地将数据库访问转换为功能

I have built a Backend API in Go, it works however I want refactor the code for the DB access layer into a function - idiomatically.

// 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
 ", 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
 ", 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)
}

I understand that I can create a method which returns (*mongoClient, err) as I utilise the client local variable later on in the code.

However I am lost as to how to implement the defer cancel() part because it executes once the method CreateStudenAccountEndpoint is at the end. But I am at a loss on how to implement this defer section in a method that will recognise that I want the defer to happen at the end of the function that calls the DB access layer method e.g CreateStudentAccountEndpoint not the actual db access method itself.

  • 写回答

1条回答 默认 最新

  • dqxboe2628 2019-02-05 08:07
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集