转到struct标签抛出错误:“字段标签必须为字符串”

时间:2019-04-01 23:16:45

标签: go

我第一次使用GO,并且正在设置一个示例API。尝试从我制作的结构返回JSON对象时,将struct标记添加到字段中时出现此错误:

“字段标签必须是字符串”和“无效的字符文字(多个字符)”。

这是我的代码细分。我在这里想念什么?

    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"'
}

1 个答案:

答案 0 :(得分:3)

您需要使用后引号来封装struct标记,而不是使用单引号来创建原始字符串文字,这样可以在标记字段中包含其他数据。

This帖子对标记进行了很好的说明,说明了标记的正确构造方式,并在需要时作为进一步解释的良好参考。

此处工作代码:

package main

import (
    "encoding/json"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

type Version struct {
    ID      string `json:"id"`
    Version string `json:"version, omitempty"`
    Sha     string `json:"sha"`
}

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)
    if err != nil {
        // handle error
    }
    json.NewEncoder(w).Encode(myJSON)
}