【发布时间】:2019-04-01 23:16:44
【问题描述】:
我是第一次使用 GO,并且正在设置一个小示例 API。在尝试从我创建的结构返回 JSON 对象时,当我将结构标记添加到我的字段时出现此错误:
“字段标签必须是字符串”和“无效字符文字(超过一个字符)”。
这是我的代码分解。我在这里错过了什么?
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/demo/v1/version", getVersion).Methods("GET")
log.Fatal(http.ListenAndServe(":8080", router))
}
func getVersion(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
version := Version{ID: "demo", Version: "1.0.0", Sha: "some hash...."}
var myJSON, err = json.Marshal(version)
json.NewEncoder(w).Encode(myJSON)
}
type Version struct {
//ERRORS on these 3 lines:
ID string 'json:"id"'
Version string 'json:"version, omitempty"'
Sha string 'json:"sha"'
}
【问题讨论】:
-
代码使用引号字符作为符文文字。使用其中一个引号字符代替字符串。
标签: go