I'm trying to validate a receipt by sending it to my custom server from iOS.
I have my NSMutableURLRequest
and set it up as so:
let body: [String: AnyObject] = ["receipt": receipt, "prod_id": productID]
let optionalJson: NSData?
do {
optionalJson = try NSJSONSerialization.dataWithJSONObject(body, options: [])
} catch _ {
optionalJson = nil
}
guard let json = optionalJson else { return }
request.HTTPBody = json
Then I send it off to my server which is written in Go, but I don't know how to then read the data.
Previously I sent only the data (in raw form, not a JSON structure), and then turned into a base 64 encoded string as so before shipping it off:
data, _ := ioutil.ReadAll(request.Body)
encodedString := base64.StdEncoding.EncodeToString(data)
But now I the JSON structure that links a prod_id
with is a string
, as well as the receipt data, which I assume is bytes
. How do I extract that into readable JSON then turn it into a base 64 encoded string as above?
I guess I'm not sure what structure the JSON would take.
That would be something like :
type Foo strut {
Bar string `json:"bar"`
}
// extract
data, err := ioutil.ReadAll(request.Body)
if err != nil {
return err
}
defer request.Body.Close()
v := &Foo{}
json.Unmarshal(data, v)
The json:"bar"
in Foo
binds the JSON struct with the Go struct
You should create struct like below:
type MyRequest struct {
Receipt string `json:"receipt"`
ProdID string `json:"prod_id"`
}
then decode request body:
func handleMyRequest(rw http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var myReq MyRequest
err := decoder.Decode(&myReq)
if err != nil {
panic()
}
log.Println(myReq)
}