I am a beginner in Golang..I have created an API which is reading the data from couchbase well but I am not able to write new fields in the json document..The code of writing new data is below:
func appendDataEndpoint(w http.ResponseWriter,req *http.Request){
var data map[string]interface{}
_ = json.NewDecoder(req.Body).Decode(&data)
fmt.Println(data)
params := mux.Vars(req)
str := params["id"]
message := message{ Student :data["student"].([]struct),//Here is another problem.How to write type of Student since it is referring to another structure."struct" is throwing type error.
College :data["college"].(string),
CollegeId: data["collegeid"].(string),
Hobbies :data["hobbies"].([]string),
Firstname: data["firstname"].(string),
Address: data["address"].(string),//New field to be inserted
Mobile: data["mobile"].(string),//New field to be inserted
}
fmt.Println(message.Address)
_,err:=bucket.Insert(str, message, 0)
if err!=nil{
fmt.Println("Error in inserting")
w.WriteHeader(401)
w.Write([]byte(err.Error()))
return
}
json.NewEncoder(w).Encode(message)
}
Still having problems.Now the updated code snippet is:
message:=message{
Student :data["student"].([]Student),//Error still exists here
College :data["college"].(string),
CollegeId :data["collegeid"].(string),
Hobbies :data["hobbies"].([]string),
Firstname :data["firstname"].(string),
Add: data["a"].(string),
Mo: data["m"].(string),
}
_,err:=bucket.Insert(str, message, 0)
The error is:
panic serving [::1]:63648: interface conversion: interface {} is nil, not []main.Student
A few things to notice since the code you provided is not fully available (what about providing code for the message
struct?):
When getting a request from the client, you unmarshal it into a map[string]{}interface
object. From there, you construct manually a message
object. Why don't you construct the message
object without having to work with type assertions? You could try doing something like so:
type Message struct {
Student []Student `json:"student"`
College String `json:"college"`
CollegeId String `json:"collegeid"`
Hobbies []String `json:"hobbies"`
FirstName String `json:"firstname"`
Address String `json:"address"`
Mobile String `json:"mobile"`
}
type Student struct {
Name String `json:"name"`
Qualifications []String `json:"qualifications"`
Email String `json:"email"`
}
var data Message
if err := json.NewDecoder(req.Body).Decode(&data); err != nil {
fmt.Println(err)
return
}
fmt.Println(data)
This would also take care of the student
struct you were having difficulties with.
I would recommend reading this article to get you started with JSON and Go.