登录
首页 >  Golang >  Go问答

在 Go 中,在 http 处理程序中使用 pgx 上下文的正确方法是什么?

来源:stackoverflow

时间:2024-04-10 08:27:37 273浏览 收藏

大家好,我们又见面了啊~本文《在 Go 中,在 http 处理程序中使用 pgx 上下文的正确方法是什么?》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

更新 1:似乎使用与 http 请求绑定的上下文可能会导致“上下文已取消”错误。但是,使用 context.background() 作为父级似乎工作正常。

    // this works, no 'context canceled' errors
    ctx, cancel := context.withtimeout(context.background(), 100*time.second)

    // however, this creates 'context canceled' errors under mild load
    // ctx, cancel := context.withtimeout(r.context(), 100*time.second)

    defer cancel()
    app.insert(ctx, record)

(更新了下面的代码示例以生成用于重现的独立示例)

在 go 中,我有一个 http 处理程序,如下代码所示。在对此端点的第一个 http 请求中,我收到 context cancelled 错误。然而,数据实际上是插入到数据库中的。在对该端点的后续请求中,不会给出此类错误,并且数据也成功插入到数据库中。

问题:我是否在 http 处理程序和 pgx queryrow 方法之间正确设置并传递了 context ? (如果没有的话还有更好的方法吗?)

如果将此代码复制到 main.go 并运行 go run main.go,转到 localhost:4444/create 并按住 ctrl-r 以产生轻微负载,您应该会看到产生一些上下文取消错误。

package main

import (
    "context"
    "fmt"
    "log"
    "math/rand"
    "net/http"
    "time"

    "github.com/jackc/pgx/v4/pgxpool"
)

type application struct {
    DB *pgxpool.Pool
}

type Task struct {
    ID     string
    Name   string
    Status string
}

//HTTP GET /create
func (app *application) create(w http.ResponseWriter, r *http.Request) {
    fmt.Println(r.URL.Path, time.Now())
    task := &Task{Name: fmt.Sprintf("Task #%d", rand.Int()%1000), Status: "pending"}
    // -------- problem code here ----
    // This line works and does not generate any 'context canceled' errors
    //ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
    // However, this linegenerates 'context canceled' errors under mild load
    ctx, cancel := context.WithTimeout(r.Context(), 100*time.Second)
    // -------- end -------
    defer cancel()
    err := app.insertTask(ctx, task)
    if err != nil {
        fmt.Println("insert error:", err)
        return
    }
    fmt.Fprintf(w, "%+v", task)
}
func (app *application) insertTask(ctx context.Context, t *Task) error {
    stmt := `INSERT INTO task (name, status) VALUES ($1, $2) RETURNING ID`
    row := app.DB.QueryRow(ctx, stmt, t.Name, t.Status)
    err := row.Scan(&t.ID)
    if err != nil {
        return err
    }
    return nil
}

func main() {
    rand.Seed(time.Now().UnixNano())
    db, err := pgxpool.Connect(context.Background(), "postgres://test:test123@localhost:5432/test")
    if err != nil {
        log.Fatal(err)
    }
    log.Println("db conn pool created")
    stmt := `CREATE TABLE IF NOT EXISTS public.task (
        id uuid NOT NULL DEFAULT gen_random_uuid(),
        name text NULL,
        status text NULL,
        PRIMARY KEY (id)
     ); `
    _, err = db.Exec(context.Background(), stmt)
    if err != nil {
        log.Fatal(err)
    }
    log.Println("task table created")
    defer db.Close()
    app := &application{
        DB: db,
    }
    mux := http.NewServeMux()
    mux.HandleFunc("/create", app.create)

    log.Println("http server up at localhost:4444")
    err = http.ListenAndServe(":4444", mux)
    if err != nil {
        log.Fatal(err)
    }
}



正确答案


TLDR:使用 r.Context() 在生产中工作正常,使用浏览器进行测试是一个问题。

HTTP 请求获取自己的上下文,该上下文在请求完成时被取消。这是一个功能,而不是一个错误。开发人员应该使用它,并在请求被客户端中断或超时时优雅地关闭执行。例如,取消的请求可能意味着客户端永远不会看到响应(事务结果),开发人员可以决定回滚该事务。

在生产中,对于正常设计/构建的 API,请求取消不会经常发生。通常,流量由服务器控制,服务器在取消请求之前返回结果。 多个Client请求不会互相影响,因为它们得到独立的go-routine和上下文。再次,我们谈论的是正常设计/构建应用程序的快乐路径。您的示例应用程序看起来不错并且应该可以正常工作。

问题在于我们如何测试应用程序。我们不创建多个独立的请求,而是使用浏览器并刷新单个浏览器会话。我没有检查究竟发生了什么,但假设浏览器终止现有请求,以便在您单击 ctrl-R 时运行新请求。服务器发现请求终止并将其作为上下文取消传达给您的代码。

尝试使用 curl 或其他创建独立请求的脚本/实用程序来测试您的代码。我确信在这种情况下您不会看到取消。

本篇关于《在 Go 中,在 http 处理程序中使用 pgx 上下文的正确方法是什么?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

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