Id 为使用 Go 的 Rest API 返回 0

我一直在尝试使用 Go 构建一些简单的后端 REST API,使用 Google App Engine 及其数据存储和前端的 AngularJS。除了编辑之外,我能够让一切正常工作。而且我不确定为什么 JSON 没有正确解组。


结构:


type Article struct {

    Key    int64    `json:"Key" datastore:"-"`

    Title  string

    Text   string   `datastore:",noindex"`

    Author string

    Tags   string

    Posted time.Time

}

加载文章时,我使用数据存储中的 id 值填充 Key 属性。示例:5593215650496512


我将该字段保留在表单上的隐藏输入中,并通过 HTTP Post 将表单内容作为 JSON 提交到 Go 后端。


在提交之前,我可以看到 Key 拥有正确的值。这是表格:


                <form name="articleForm" ng-submit="saveArticle(article)">

                    <fieldset>

                        <input type="hidden" name="key" ng-value="article.Key" />

                        <div class="form-group">

                            <input class="form-control" ng-model="article.Title" placeholder="Title" name="title" type="text" required autofocus />

                            <div class="alert alert-danger" ng-show="articleForm.Title.$invalid && articleForm.Title.$dirty">

                                <ul>

                                    <li ng-show="articleForm.title.$error.required">this field is required</li>

                                </ul>

                            </div>

                        </div>


紫衣仙女
浏览 172回答 1
1回答

达令说

当您解组到您的文章时,您忽略了错误。您应该看到json: cannot unmarshal string into Go value of type int64,因为Key正文中的值被格式化为字符串。如果这是您所期望的,那么您可以通过将string选项添加到标签来告诉 json 包使用它:type Article struct {&nbsp; &nbsp; Key&nbsp; &nbsp; int64&nbsp; &nbsp; `json:"Key,string" datastore:"-"`&nbsp; &nbsp; Title&nbsp; string&nbsp; &nbsp; Text&nbsp; &nbsp;string&nbsp; &nbsp;`datastore:",noindex"`&nbsp; &nbsp; Author string&nbsp; &nbsp; Tags&nbsp; &nbsp;string&nbsp; &nbsp; Posted time.Time}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go