The code is available for download from:
For the marshaling and unmarshaling of JSON, golang already provide us with the capability to do that out of the box. We just need to provide it with
the necessary structure or variable to do it for us. The package to use is "encoding/json" and the two main functions are json.Marshal and json.Unmarshal.
Let's take LogonStr which is the structure holding the logon data and this is how we will marshal it:
type LogonStr struct { Username string `json:"username"` Password string `json:"password"` } logon := LogonStr{"johnny","bravo"} buf, err := json.Marshal(logon)The part after the field names that start with `json: indicates that for the JSON we want different fieldnames (in this case just the lower case). Golang expect the fieldnames in the struct to have and initial capital letter to be exportable else json.Marshal and json.Unmarshal cannot see them (they are essentially then private).
logon := struct { Username string `json:"username"` Password string `json:"password"` }{"johnny","bravo"} buf, err := json.Marshal(logon)In this case the structure is only going to be used to generate json once. We can in fact do it all in one go:
buf, err := json.Marshal(struct { Username string `json:"username"` Password string `json:"password"` }{"johnny","bravo"})
logon := LogonStr{} err := json.Unmarshal(buf,&logon)First an empty struct of the type that you want to unmarshal to is created (LogonStr in this case). Then the byte array (buf) and the empty struct is passed to json.Unmarshal. The data will be placed within their correct fields and if an error is experienced it will be returned.
result := struct { Status bool `json:"status"` Data json.RawMessage `json:"data"` }{} err := json.Unmarshal(buf,&result) if err != nil { // Do some error handling } else { if result.Status { var sesskey int64 err := json.Unmarshal(result.Data,&sesskey) // Do something with sesskey } else { var msg string err := json.Unmarshal(result.Data,&msg) // Do something with msg } }Here we have a structure that is being returned and the status can be true (which indicates success and let's assume an int64 session key is returned then data) or false (which indicates failure and data has a string message for the error then).
On the server side one has to include the following in all handling of calls:
w.Header().Add("Access-Control-Allow-Origin", "*") w.Header().Add("Content-Type", "text/json;charset=UTF-8")This is to ensure tin the case a web browser communicates with the server it will allow cross domain AJAX calls.
buf, err := ioutil.ReadAll(r.Body)This is straight forward and just reads everything in the body and place it into buf (a byte array) or return an error. This byte array can then be passed straigth to a call of json.Unmarshal. The rest of the code should be relative self explanitory.