dongxie45083 2019-04-01 23:16
浏览 85
已采纳

Go struct标记抛出错误:“字段标记必须是字符串”

I'm using GO for the first time and am setting up a little example API. In trying to return a JSON object from a struct that I made, I get this error when I add a struct tag to my fields:

"field tag must be a string" and "invalid character literal (more than one character)".

Here's my code breakdown. What am I missing here?

    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条回答 默认 最新

  • dongzhong7443 2019-04-01 23:24
    关注

    You need to encapsulate your struct tags with back quotes instead of using single quotes to create raw string literals which can allow for the inclusion of additional data in the tag field.

    This post gives a good explanation of tags, how they are constructed properly and should serve as a good reference for further explanation if needed.

    Working code here:

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog