0

在 POST 请求之后,我希望将最后插入的记录编组到 json 中,但返回的是一个空正文。我哪里做得不好?

package models


import (
    "encoding/json"
    "errors"
    "flag"
    "fmt"
    "log"
    "net/http"
    "strconv"

    "github.com/go-chi/chi"
    "github.com/google/jsonapi"
    "github.com/thedevsaddam/renderer"
    "github.com/xo/dburl"
)

var rnd = renderer.New()

var flagVerbose = flag.Bool("v", false, "verbose")

var FlagURL = flag.String("url", "postgres://postgres:@127.0.0.1/sweb", "url")

// Page represents a row from 'public.pages'.
type Page struct {
    Tag   string `jsonapi:"attr,tag"`      // tag
    Body  string `jsonapi:"attr,body"`     // body
    Slug  string `jsonapi:"attr,slug"`     // slug
    Title string `jsonapi:"attr,title"`    // title
    ID    int    `jsonapi:"primary,pages"` // id
    Link  string `jsonapi:"attr,link"`     // link

    // xo fields
    _exists, _deleted bool
}

func (page Page) JSONAPILinks() *jsonapi.Links {
    return &jsonapi.Links{
        "self": fmt.Sprintf("https://%d", page.ID),
    }
}

我相信这是罪魁祸首。插入记录后,它应该返回指定的最后插入的记录。

func (p *Page) PInsert(db XODB) (*Page, error) {
    var err error

    // if already exist, bail
    if p._exists {
        return p, errors.New("insert failed: already exists")
    }

    // sql insert query, primary key provided by sequence
    const sqlstr = `INSERT INTO public.pages (` +
        `tag, body, slug, title` +
        `) VALUES (` +
        `$1, $2, $3, $4` +
        `) RETURNING id, tag, body, title`

    // run query
    XOLog(sqlstr, p.Tag, p.Body, p.Slug, p.Title)
    err = db.QueryRow(sqlstr, p.Tag, p.Body, p.Slug, p.Title).Scan(&p.ID, &p.Tag, &p.Body, &p.Title)
    if err != nil {
        return p, err
    }

    // set existence
    p._exists = true

    return p, nil
}

Update 更新数据库中的 Page 并返回最后插入的记录。这同样适用于更新功能

func (p *Page) Update(db XODB) (*Page, error) {
    var err error

    // if doesn't exist, bail
    if !p._exists {
        return p, errors.New("update failed: does not exist")
    }

    // if deleted, bail
    if p._deleted {
        return p, errors.New("update failed: marked for deletion")
    }

    // sql query
    const sqlstr = `UPDATE public.pages SET (` +
        `tag, body, slug, title` +
        `) = ( ` +
        `$1, $2, $3, $4` +
        `) WHERE id = $5`

    // run query
    XOLog(sqlstr, p.Tag, p.Body, p.Slug, p.Title, p.ID)
    _, err = db.Exec(sqlstr, p.Tag, p.Body, p.Slug, p.Title, p.ID)
    return p, err
}

func (p *Page) PSave(db XODB) (*Page, error) {
    if p.Exists() {
        return p.Update(db)
    }

    return p.PInsert(db)
}


func NewPage(w http.ResponseWriter, r *http.Request) {

    db, err := dburl.Open(*FlagURL)
    defer db.Close()
    if err != nil {
        log.Fatal(err)
    }

    var page Page

    //page := new(Page)

    if err := jsonapi.UnmarshalPayload(r.Body, &page); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }


    p, err := page.PSave(db)
    if err != nil {
        fmt.Println(err)
        if err := jsonapi.MarshalPayload(w, p); err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            fmt.Println(err)
        }


    }


    w.Header().Set("Content-Type", jsonapi.MediaType)
    w.WriteHeader(http.StatusCreated)

}

这是我认为问题正在发生的最后一个功能。最后插入的记录应该被编组为 json。

4

1 回答 1

1

您的最后一段代码包含许多错误。相关部分(没有无用和令人困惑的 Printlns)是:

p, err := page.PSave(db)
if err != nil {
    if err := jsonapi.MarshalPayload(w, p); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

w.Header().Set("Content-Type", jsonapi.MediaType)
w.WriteHeader(http.StatusCreated)

主要错误是json.MarshalPayload仅在 时调用err != nil。换句话说,只有在保存失败时才对页面进行序列化。

第二个错误是会jsonapi.MarshalPayload调用Write. http.ResponseWriter这会将所有后续调用 变为Header().SetWriteHeader操作。

更正确的代码如下所示。

// 1. Save the page in the database, bail on error
p, err := page.PSave(db)
if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return 
}

// 2. Marshal the page into an intermediate buffer, bail on error
var buf bytes.Buffer
if err := jsonapi.MarshalPayload(&buf, p); err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return 
}

// 3. Write the entire response; failures to write the intermediate buffer
// cannot be communicated over HTTP
w.Header().Set("Content-Type", jsonapi.MediaType)
w.WriteHeader(http.StatusCreated)
if _, err := buf.WriteTo(w); err != nil {
    log.Printf("failed to write response: %v", err)
    return 
}
于 2019-03-08T07:39:52.493 回答