Headers 已经写好了。想用 500 覆盖状态码 200

Headers were already written. Wanted to override status code 200 with 500

这是我的 gorilla-websocket websocket 处理程序:

func wshandler(w http.ResponseWriter, r *http.Request) {
    wsupgrader.CheckOrigin = func(r *http.Request) bool {
        return true
    }
    c, err := wsupgrader.Upgrade(w, r, nil)
    if err != nil {
        fmt.Println(err)
        return
    }
    for {
        var m WebsocketGeneralClientMessage
        err := c.ReadJSON(&m)
        if err != nil {
            log.Println(err)
            break
        }
        switch m.Type {
        case "register":
            err := Register(c, m)
            if err != nil {
                log.Println(err)
            }
        }
    }
}

根据 type,我想对不同类型的消息做出不同的响应。我只有 register 类型。出于某种原因,Register 函数给我以下错误:

Headers were already written. Wanted to override status code 200 with 500
func Register(c *websocket.Conn, m WebsocketGeneralClientMessage) error {
    var d RegisterData
    json.Unmarshal(m.Data, &d)
    if len(d.Email) < 6 || len(d.Email) > 64 {
        _error := "The email length must be between 6 and 64 characters"
        c.WriteJSON(WebsocketGeneralServerMessage{Type: "register", Status: "error", Data: map[string]interface{}{"text": _error}})
        return errors.New(_error)
    }
    if len(d.Password) < 6 || len(d.Password) > 32 {
        _error := "The password length must be between 6 and 64 characters"
        c.WriteJSON(WebsocketGeneralServerMessage{Type: "register", Status: "error", Data: map[string]interface{}{"text": "The password length must be between 6 and 64 characters"}})
        return errors.New(_error)
    }
    err := checkmail.ValidateFormat(d.Email)
    if err != nil {
        _error := "The email format is not correct"
        c.WriteJSON(WebsocketGeneralServerMessage{Type: "register", Status: "error", Data: map[string]interface{}{"text": _error}})
        return errors.New(_error)
    }

    var rawUUID pgtype.UUID
    var exists bool

    err = Pool.QueryRow(context.Background(), `SELECT EXISTS(SELECT "email" FROM "account" WHERE "email"=)`, d.Email).Scan(&exists)
    if err != nil {
        _error := "An error occured while creating the account. Please send a message in #bugs at our Discord."
        c.WriteJSON(WebsocketGeneralServerMessage{Type: "register", Status: "error", Data: map[string]interface{}{"text": _error}})
        return errors.New(_error)
    }

    if exists {
        _error := "An error occured while creating the account. Please send a message in #bugs at our Discord."
        c.WriteJSON(WebsocketGeneralServerMessage{Type: "register", Status: "error", Data: map[string]interface{}{"text": _error}})
        return errors.New(_error)
    }

    err = Pool.QueryRow(context.Background(), `INSERT INTO "account" ("email", "password") VALUES(, ) RETURNING "uuid"`, d.Email, d.Password).Scan(&rawUUID)
    if err != nil {
        _error := "An error occured while creating the account. Please send a message in #bugs at our Discord."
        c.WriteJSON(WebsocketGeneralServerMessage{Type: "register", Status: "error", Data: map[string]interface{}{"text": _error}})
        return errors.New(_error)
    }

    uuid, err := rawUUID.Value()
    if err != nil {
        _error := "An error occured while saving the account to the database"
        c.WriteJSON(WebsocketGeneralServerMessage{Type: "register", Status: "error", Data: map[string]interface{}{"text": _error}})
        return errors.New(_error)
    }

    c.WriteJSON(WebsocketGeneralServerMessage{Type: "register", Status: "success", Data: map[string]interface{}{"uuid": uuid}})
    return nil
}

我知道问题出在 var exists bool 之后的函数的后半部分,因为我删除了那部分并且程序没有给出错误。可能是什么问题?显然出现错误是因为我应该覆盖响应但是每个 c.WriterJSONreturn 结尾所以不应该有任何响应覆盖。

这是完整的错误:

2020/09/21 13:58:01 [Recovery] 2020/09/21 - 13:58:01 panic recovered:
GET /ws HTTP/1.1
Host: 192.168.0.41
Accept-Encoding: gzip
Connection: Upgrade
Origin: http://192.168.0.41
Sec-Websocket-Key: 9E7mNgJ4qH4VsbWDJuEaWQ==
Sec-Websocket-Version: 13
Upgrade: websocket
User-Agent: okhttp/3.14.4


runtime error: invalid memory address or nil pointer dereference
/usr/local/Cellar/go/1.15/libexec/src/runtime/panic.go:212 (0x104c992)
    panicmem: panic(memoryError)
/usr/local/Cellar/go/1.15/libexec/src/runtime/signal_unix.go:720 (0x104c812)
    sigpanic: panicmem()
/Users/virtumonde/go/pkg/mod/github.com/jackc/pgx/v4@v4.8.1/pgxpool/pool.go:355 (0x14c21ba)
    (*Pool).Acquire: res, err := p.p.Acquire(ctx)
/Users/virtumonde/go/pkg/mod/github.com/jackc/pgx/v4@v4.8.1/pgxpool/pool.go:419 (0x14c2459)
    (*Pool).QueryRow: c, err := p.Acquire(ctx)
/Users/virtumonde/Desktop/dev/terminus/terminus-server/ws_routes.go:46 (0x14cfa0b)
    Register: err = Pool.QueryRow(context.Background(), `SELECT EXISTS(SELECT "email" FROM "account" WHERE "email"=)`, d.Email).Scan(&exists)
/Users/virtumonde/Desktop/dev/terminus/terminus-server/ws.go:34 (0x14cf3e4)
    wshandler: err := Register(c, m)
/Users/virtumonde/Desktop/dev/terminus/terminus-server/main.go:44 (0x14d07ea)
    main.func1: wshandler(c.Writer, c.Request)
/Users/virtumonde/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x13a5eba)
    (*Context).Next: c.handlers[c.index](c)
/Users/virtumonde/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/recovery.go:83 (0x13b1cc4)
    RecoveryWithWriter.func1: c.Next()
/Users/virtumonde/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x13a5eba)
    (*Context).Next: c.handlers[c.index](c)
/Users/virtumonde/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/logger.go:241 (0x13b0dc4)
    LoggerWithConfig.func1: c.Next()
/Users/virtumonde/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x13a5eba)
    (*Context).Next: c.handlers[c.index](c)
/Users/virtumonde/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/gin.go:409 (0x13a8c79)
    (*Engine).handleHTTPRequest: c.Next()
/Users/virtumonde/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/gin.go:367 (0x13a84ec)
    (*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/usr/local/Cellar/go/1.15/libexec/src/net/http/server.go:2843 (0x12676a2)
    serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/usr/local/Cellar/go/1.15/libexec/src/net/http/server.go:1925 (0x1263c6c)
    (*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
/usr/local/Cellar/go/1.15/libexec/src/runtime/asm_amd64.s:1374 (0x106bb60)
    goexit: BYTE    [=14=]x90   // NOP

我发现了问题。我的 Pool 变量(我使用它连接到我的 Postgres 数据库)

var Pool *pgxpool.Pool

在初始化时被另一个局部变量遮盖了。

Pool, err := pgxpool.Connect(context.Background(), "postgres://postgres:@localhost:5432/database")

所以我把初始化改成了

var err error
Pool, err = pgxpool.Connect(context.Background(), "postgres://postgres:@localhost:5432/database")

显然,数据库代码因此被执行了不止一次。