-1

I am trying to send the following data via a POST HTTP request to an API:

{ 
   "client_interface":{ 
      "source_address":source,
      "destination_address":destn,
      "message":encrypted_msg,
      "business_event_url":settings.Message_CallbackURL
   },
   "server_interface":{ 
      "message_id":msg_id
   }
}

The API is responding with the following error:

{ 
   "Meta":{ 
      "Requestid":12301343169471000
   },
   "Error":{ 
      "Message":"Request body contains badly-formed JSON (at position 51)",
      "Param":""
   }
}

CODE:

apiUrl := "http://example.com"
tr := &http.Transport{
    TLSClientConfig: &tls.Config{InsecureSkipVerify : true},
}

jsonStr := []byte(`{
        "client_interface": {
          "source_address": source,
          "destination_address": destn,
          "message": encrypted_msg,
          "business_event_url": settings.Message_CallbackURL
        },
        "server_interface": {
          "message_id": msg_id
        }
    }`)

req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(jsonStr)) 
fmt.Println("req..........",req)
if err!=nil{
    log.Println("err in http req..............",err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("requestid", msg_id)
req.Header.Set("Authorization", "Bearer "+conn_token)
client := &http.Client{Transport: tr}
resp, err := client.Do(req)
if resp!=nil{
    body, _ := ioutil.ReadAll(resp.Body)
}

Using struct :

package main
import (
    "fmt"
    "net/http"
    "io/ioutil"
    "bytes"
    //"crypto/tls"
    "encoding/json"
)

type client_interface struct {
        source_address string `json:"string"`
        destination_address uint64 `json:"uint64"`
        message string `json:"string"`
        business_event_url string `json:"string"`
    }
type server_interface struct { 
    message_id uint64 `json:"uint64"`
    }
type data struct {
    client_interface client_interface `json:"client_interface"`
    server_interface server_interface `json:"server_interface"`
}


func main() {
    url := "https://example.com"
    fmt.Println("URL:>", url)


    client_interface := client_interface{}
    server_interface := server_interface{}

    client_interface.source_address="1"
    client_interface.destination_address=1111111111
    client_interface.message="khsjhdjks"
    client_interface.business_event_url="http://callbackurl-hdfc"

    server_interface.message_id=8210993557215399651

    fmt.Println("server_interface..........",server_interface)
    fmt.Println("client_interface..........",client_interface)

    body1 := &data{
                client_interface: client_interface,
                server_interface: server_interface,
    }
    fmt.Println("body1..........",body1)
    t,e:=json.Marshal(body1)
    fmt.Println("t..........",t)            
    fmt.Println("e..........",e)            


    req, err := http.NewRequest("POST", url, bytes.NewReader(t))
    fmt.Println("req......",req)
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("requestid", "8210993557215399651")
    req.Header.Set("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IkJCOENlRlZxeWFHckdOdWVoSklpTDRkZmp6dyIsImtpZCI6IkJCOENlRlZxeWFHckdOdWVoSklpTDRkZmp6dyJ9.eyJhdWQiOiJhcGk6Ly90cC1kZXYtdGFubGEtYXBpIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvY2JhYThhYmItZTcwZi00YmI4LWIwNDQtZmZiZjAwNzk0NzkwLyIsImlhdCI6MTU3NTg5MTI3NCwibmJmIjoxNTc1ODkxMjc0LCJleHAiOjE1NzU4OTUxNzQsImFjciI6IjEiLCJhaW8iOiI0MlZnWU9EY3JjenlhZXIxdkRMRDVlNHVtWUxha1UrRUplOVYrZGVlRFgrOTNUMytNRGNBIiwiYW1yIjpbInB3ZCJdLCJhcHBpZCI6IjFmMjI1N2ZlLWIzYjktNGQ2Ny05M2YyLWRjNjM2N2Q2MGM4MCIsImFwcGlkYWNyIjoiMCIsImlwYWRkciI6IjE0LjE0My4xODcuMjUwIiwibmFtZSI6ImhkZmMuMTEiLCJvaWQiOiIzOGQxMGFlNS01OGYyLTQ0NjUtYTFkOC04YTc0NDAzYjc5MmEiLCJzY3AiOiJ1c2VyX2ltcGVyc29uYXRpb24iLCJzdWIiOiIzNDdUd0ZwYUw5MDhmOXlNRWlGOWNHMU84THFQYmJxZk45VzhyQWVEX1prIiwidGlkIjoiY2JhYThhYmItZTcwZi00YmI4LWIwNDQtZmZiZjAwNzk0NzkwIiwidW5pcXVlX25hbWUiOiJoZGZjLjExQFRhbmxhUHJvZHVjdC5vbm1pY3Jvc29mdC5jb20iLCJ1cG4iOiJoZGZjLjExQFRhbmxhUHJvZHVjdC5vbm1pY3Jvc29mdC5jb20iLCJ1dGkiOiJuS05TTXRsT3VFeXMtQjRIOGJ3TEFRIiwidmVyIjoiMS4wIn0.F5H9WCOktau3JaqNyWM91A5jFpJ9eJE99fBWvqDq9kOfCk3OCJnHFKXtIaIA7MoqbxWpNZt1yWpVKuw8gd2Lg_9nfUvvXts2DJHVQN0EqQmFUyWTzhdLW8ZVi6E9RtXK2aEWrI2TVceL5C2wbYOQYfvV4LzjTuNbs6k_20cQ0nD6oO1Id16VVFQWy9yKvpDzsTrvlQdFBZeohIfyL9XWKa8DOk0gxe4bjC7OFmuMsF3FZE5XPaQPHOJ3ejlZJiApml2TlRHnvLpkn1biE3NTAu9aO2lE262lyLg8ZaU0sbPuQaS8P797a-outxLvKEMh07895mA9g6vMxEdRV9X2eA")

    client := &http.Client{}
    resp, err := client.Do(req)
    fmt.Println("err.............",err)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Println("response Status:", resp.Status)
    fmt.Println("response Headers:", resp.Header)
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("response Body:", string(body))
}
Vani Polnedi
  • 595
  • 2
  • 4
  • 19
  • All of the values in your json are missing quotes around them. It should be `"source_address": "source"`, etc. not `"source_address": source`. – mkopriva Dec 09 '19 at 11:04
  • 3
    ... although it seems a bit like you're trying to refer to actual variables inside the raw string, which is not possible in Go. Instead you should declare a struct type with a structure equivalent to that of the json, initialize it and set the fields to the desired values and then marshal that struct instance with the `encoding/json` package. – mkopriva Dec 09 '19 at 11:06
  • i have taken source,destn,encrypted_msg,Message_CallbackURL,msg_id as constant values – Vani Polnedi Dec 09 '19 at 11:31
  • tried by taking structure also .. but i'm getting error as 502 Bad Gateway – Vani Polnedi Dec 09 '19 at 11:31
  • 1
    Constant values or variables, it doesn't matter, using Go identifiers in a string will not interpolate their values into the string automagically. If you want to build the string yourself you can use concatenation for example, or, as already mentioned, use a struct and the `encoding/json` package. – mkopriva Dec 09 '19 at 12:11
  • *"tried by taking structure also .. but i'm getting error as 502 Bad Gateway"* well if you want help with that you'll need to include the code from that attempt in the question as well. – mkopriva Dec 09 '19 at 12:12
  • added code ... can u pls check once now – Vani Polnedi Dec 09 '19 at 12:20
  • You need to export the fields of the struct for them to be accessible by the `encoding/json` package. – mkopriva Dec 09 '19 at 12:22
  • try nested map and convert to JSON https://stackoverflow.com/questions/44305617/nested-maps-in-golang for converting map to json - jsonString, err := json.Marshal(datas) – ASHMIL Dec 09 '19 at 12:26

1 Answers1

0

First of all: please use gofmt

Your first code can't work because golang doesn't substitute variables inside string. It's better to use structs.

With structs it's not working because you named struct fields from lower case latter, it means "private" fields in go. So encoding/json package can't access them and just skip them. Use Capital first letters.

Another fix is about 'json:"tag"' - here tag means encoded field name, not type. So instead of 'json:"string"' you should use 'json:"message_id"' or so. You can specify type like this 'json:"field_name,type"' or like this 'json:",type"' but encoding/json guess type on his own.

(I used wrong quotes in tags because of markdown)

I used netcat -l 5000 to listen on 5000 port on localhost and print everything to the terminal. Then I changed url to http://localhost:5000 (not https) to send request to myself. You need to restart netcat each time to work.

And I made logging a bit more readable.

Also it's CamelCase naming convention in go.

Changed your code a little bit

package main

import (
    "bytes"
    "flag"
    "fmt"
    "io/ioutil"
    "net/http"

    //"crypto/tls"
    "encoding/json"

    "github.com/nikandfor/tlog"
)

type ClientInterface struct {
    SourceAddress      string `json:"source_address"`
    DestinationAddress uint64 `json:"destination_address"`
    Message            string `json:"message"`
    BusinessEventURL   string `json:"business_event_url"`
}
type ServerInterface struct {
    MessageID uint64 `json:"message_id"`
}
type Data struct {
    ClientInterface ClientInterface `json:"client_interface"`
    ServerInterface ServerInterface `json:"server_interface"`
}

var (
    // use command line flag. so run like so:
    // go run ./file.go -addr https://example.com
    addr = flag.String("addr", "http://localhost:5000", "address to send data to")
)

func main() {
    flag.Parse() // DO NOT FORGET TO PARSE FLAGS

    fmt.Println("URL:>", *addr)

    clientInterface := ClientInterface{
        SourceAddress:      "1",
        DestinationAddress: 8886121111,
        Message:            "khsjhdjks",
        BusinessEventURL:   "http://callbackurl-hdfc",
    }

    serverInterface := ServerInterface{
        MessageID: 8210993557215399651,
    }

    tlog.Printf("server_interface %+v", serverInterface)
    tlog.Printf("client_interface %+v", clientInterface)

    body1 := &Data{
        ClientInterface: clientInterface,
        ServerInterface: serverInterface,
    }
    tlog.Printf("body %+v", body1)
    t, err := json.Marshal(body1)
    if err != nil {
        panic(err)
    }
    tlog.Printf("marshalled: %s", t)

    req, err := http.NewRequest("POST", *addr, bytes.NewReader(t))
    tlog.Printf("req %v", req)
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("requestid", "8210993557215399651")
    req.Header.Set("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IkJCOENlRlZxeWFHckdOdWVoSklpTDRkZmp6dyIsImtpZCI6IkJCOENlRlZxeWFHckdOdWVoSklpTDRkZmp6dyJ9.eyJhdWQiOiJhcGk6Ly90cC1kZXYtdGFubGEtYXBpIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvY2JhYThhYmItZTcwZi00YmI4LWIwNDQtZmZiZjAwNzk0NzkwLyIsImlhdCI6MTU3NTg5MTI3NCwibmJmIjoxNTc1ODkxMjc0LCJleHAiOjE1NzU4OTUxNzQsImFjciI6IjEiLCJhaW8iOiI0MlZnWU9EY3JjenlhZXIxdkRMRDVlNHVtWUxha1UrRUplOVYrZGVlRFgrOTNUMytNRGNBIiwiYW1yIjpbInB3ZCJdLCJhcHBpZCI6IjFmMjI1N2ZlLWIzYjktNGQ2Ny05M2YyLWRjNjM2N2Q2MGM4MCIsImFwcGlkYWNyIjoiMCIsImlwYWRkciI6IjE0LjE0My4xODcuMjUwIiwibmFtZSI6ImhkZmMuMTEiLCJvaWQiOiIzOGQxMGFlNS01OGYyLTQ0NjUtYTFkOC04YTc0NDAzYjc5MmEiLCJzY3AiOiJ1c2VyX2ltcGVyc29uYXRpb24iLCJzdWIiOiIzNDdUd0ZwYUw5MDhmOXlNRWlGOWNHMU84THFQYmJxZk45VzhyQWVEX1prIiwidGlkIjoiY2JhYThhYmItZTcwZi00YmI4LWIwNDQtZmZiZjAwNzk0NzkwIiwidW5pcXVlX25hbWUiOiJoZGZjLjExQFRhbmxhUHJvZHVjdC5vbm1pY3Jvc29mdC5jb20iLCJ1cG4iOiJoZGZjLjExQFRhbmxhUHJvZHVjdC5vbm1pY3Jvc29mdC5jb20iLCJ1dGkiOiJuS05TTXRsT3VFeXMtQjRIOGJ3TEFRIiwidmVyIjoiMS4wIn0.F5H9WCOktau3JaqNyWM91A5jFpJ9eJE99fBWvqDq9kOfCk3OCJnHFKXtIaIA7MoqbxWpNZt1yWpVKuw8gd2Lg_9nfUvvXts2DJHVQN0EqQmFUyWTzhdLW8ZVi6E9RtXK2aEWrI2TVceL5C2wbYOQYfvV4LzjTuNbs6k_20cQ0nD6oO1Id16VVFQWy9yKvpDzsTrvlQdFBZeohIfyL9XWKa8DOk0gxe4bjC7OFmuMsF3FZE5XPaQPHOJ3ejlZJiApml2TlRHnvLpkn1biE3NTAu9aO2lE262lyLg8ZaU0sbPuQaS8P797a-outxLvKEMh07895mA9g6vMxEdRV9X2eA")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    tlog.Printf("response Status: %v", resp.Status)
    tlog.Printf("response Headers: %v", resp.Header)
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    tlog.Printf("response Body: %s", string(body))
}
$ nc -l 5000
POST / HTTP/1.1
Host: localhost:5000
User-Agent: Go-http-client/1.1
Content-Length: 92
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IkJCOENlRlZxeWFHckdOdWVoSklpTDRkZmp6dyIsImtpZCI6IkJCOENlRlZxeWFHckdOdWVoSklpTDRkZmp6dyJ9.eyJhdW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vlQdFBZeohIfyL9XWKa8DOk0gxe4bjC7OFmuMsF3FZE5XPaQPHOJ3ejlZJiApml2TlRHnvLpkn1biE3NTAu9aO2lE262lyLg8ZaU0sbPuQaS8P797a-outxLvKEMh07895mA9g6vMxEdRV9X2eA
Content-Type: application/json
Requestid: 8210993557215399651
Accept-Encoding: gzip

{"client_interface":{"source_address":"1","destination_address":8886121111,"message":"khsjhdjks","business_event_url":"http://callbackurl-hdfc"},"server_interface":{"message_id":8210993557215399651}}

Is it what you've expected?

And the last. I strongly suggest you to read https://golang.org/doc/effective_go.html

Nikifor
  • 211
  • 1
  • 4