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