import (
"database/sql"
"encoding/json"
"fmt"
"io"
"net/http"
jsonpatch "github.com/evanphx/json-patch"
"github.com/gin-gonic/gin"
"github.com/jasonalansmith/maelstrom-platform-api/database"
)
type Issue struct {
SysId uint `json:"sysid,omitempty"`
Identifier string `json:"identifier,omitempty"`
SummaryBrief string `json:"summarybrief,omitempty"`
SummaryLong string `json:"summarylong,omitempty"`
}
func patchIssue(ctx *gin.Context) {
id := ctx.Param("sysid")
// body := Issue{}
//data, err := ctx.GetRawData()
//if err != nil {
// ctx.AbortWithStatusJSON(400, "Issue not defined.")
// return
//}
//err = json.Unmarshal(data, &body)
//if err != nil {
// fmt.Println(err)
// ctx.AbortWithStatusJSON(400, "Bad input.")
// return
//}
iss := Issue{}
sqls := "SELECT * FROM issue WHERE sysid = $1"
res := database.Db.QueryRow(sqls, id)
err := res.Scan(&iss.SysId, &iss.Identifier, &iss.SummaryBrief,
&iss.SummaryLong)
if err == sql.ErrNoRows {
ctx.AbortWithStatusJSON(400, "Issue does not exist.")
return
}
issueBytes, err := json.Marshal(iss)
if err != nil {
fmt.Println("Error creating patch json ", err.Error())
return
}
patchJSON, err := io.ReadAll(ctx.Request.Body)
fmt.Println(string(patchJSON))
if err != nil {
fmt.Println(err)
}
patch, err := jsonpatch.DecodePatch(patchJSON)
if err != nil {
fmt.Println("Error decoding patch json ", err.Error())
return
}
patchedIssue, err := patch.Apply(issueBytes)
if err != nil {
fmt.Println("Error applying patch json ", err.Error())
return
}
fmt.Println(patchedIssue)
}
使用Go版本:
go版本go1.21.1 Linux/amd 64
当我运行这段代码时,我得到以下错误:
json:无法将对象解组为jsonpatch类型的Go值。Patch
我从here中改编了这段代码。
当我这样做:
fmt.Println(string(patchJSON))
我得到了看起来有效的JSON。
冒犯的一行是:
patch,err:= jsonpatch.DecodePatch(patchJSON)
我在openSuse Tumbleweed上使用curl来调用API:
curl -d '{“op”:“replace”,“path”:“/summarybrief”,“value”:“第二个测试问题”-X PATCH http://localhost:8080/issue/22-H“内容类型:application/json”
我做错了什么,得到这个错误?谢谢你,谢谢
1条答案
按热度按时间wixjitnu1#
{"op": "replace", "path": "/summarybrief", "value": "Second Test Issue"}
不是有效的修补程序。根据the spec:JSON Patch文档是表示对象数组的JSON [RFC 4627]文档。
因此,补丁需要是一个数组-例如。
[{"op": "replace", "path": "/summarybrief", "value": "Second Test Issue"}]
将按照以下示例(playground)工作: