Sending Json Body to a API request

hi i have to call an api with Dynamic Body which is application/json
how to send

  1. {
    “username”: “{{username}}”
    }
    2){
    “username”: “{{username}}”,
    “password”:"{{password}}"
    }
    1 and 2 depends on api so i need someway to send it dynamically
    didnt work :frowning:
    b := user.Username
    var jsonStr = []byte(b)

     					req, _ := http.NewRequest("POST", jmb_rid_url,bytes.NewBuffer(jsonStr) )
    

r.Body is empty , how to send this Json body to my next api request
thanks

You probably want the omitempty tag in JSON struct tags.

package main

import (
	"encoding/json"
	"fmt"
)

type Demo struct {
	Username string `json:"username"`
	Password string `json:"password,omitempty"`
}

func main() {
	var data Demo
	data.Username = "some-user"
	b, err := json.Marshal(data)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))

	data.Password = "some-password"
	b, err = json.Marshal(data)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))

}

https://play.golang.org/p/BmoGb6-N2in

hi thanks for this .
i am trying to fix a part of code which looks like this :slight_smile:
else if request_uri != url_check {
check_jmb_token := r.Header.Get(“Authorization”)
fmt.Println("checking if this is jumbo token or not ", check_jmb_token)
jmb_token := strings.Split(check_jmb_token, “:”)
fmt.Println(“token checking JMB”, jmb_token[0])

				if jmb_token[0] == "Bearer JMB_" {
					request_url_jmb := r.RequestURI

					fmt.Println("request_url_jmb--->", request_url_jmb)
					fmt.Println("JMB_ token was recived pass to RID")
					jmb_rid_url := rid_env_url + request_url_jmb
					fmt.Println("jmb_rid_url", jmb_rid_url)
					fmt.Println("jmb_rid_url",jmb_rid_url)
					data := url.Values{}
					if user.Username != ""{

						data.Set("username", user.Username)

					}
					if user.GrantType != ""{

						data.Add("grant_type", user.GrantType)

					}
					if user.GrantType != ""{

						data.Add("password", user.Password)

					}

					payload := data.Encode()
					fmt.Println("mrk see payload",payload)
		

				
						fmt.Println("printing body", payload)
						payload_new :=strings.NewReader(payload)
						buf := new(bytes.Buffer)
						buf.ReadFrom(r.Body)
						c_type :=r.Header.Get("Content-Type")
						fmt.Println("c_type",c_type)
						newStr := buf.String()
						var ptr = new(string)
						*ptr = newStr
						fmt.Println("&ptr", &ptr, *ptr)
					
						fmt.Println("----payload_new-----",payload_new)
						fmt.Print("strings.NewReader(user.Username)",strings.NewReader(user.Username))
					

					b := user.Username
					var jsonStr = []byte(b)

						req, _ := http.NewRequest("POST", jmb_rid_url,bytes.NewBuffer(jsonStr) )
						
				
						jmb_bearer_token := "Bearer " + jmb_token[1]
						fmt.Println("sending request to RID :jmb_bearer_token ", jmb_bearer_token)
						req.Header.Add("Authorization", "Bearer xxxxxxx")
						//fmt.Println("jmb_bearer_token",jmb_bearer_token)
						req.Header.Add("Content-Type", "Application/json")
						//fmt.Println("Content-Type", c_type)
						fmt.Println("see request ------->",req)
						resp, _ := http.DefaultClient.Do(req)
						defer resp.Body.Close()
						bodynew, _ := ioutil.ReadAll(resp.Body)
						fmt.Println("------bodynew--------", string(bodynew))
						fmt.Println("response given: ",resp)
				if resp.StatusCode >= 200 && resp.StatusCode <= 299 {
					fmt.Println("here status is 200")
					fmt.Fprintf(w, "%s", bodynew)

				}else if resp.StatusCode >=500 && resp.StatusCode <= 599{
						fmt.Println("%T", "final response ", resp)
					fmt.Println("gid_env_url+r.RequestURI", gid_env_url+r.RequestURI)
					fmt.Println("came to gid as rid failed with the following payload ", *ptr)
					pay := strings.NewReader(*ptr)
					req_1, _ := http.NewRequest("POST", gid_env_url+r.RequestURI, pay)
					fmt.Println("Bearerjmb_token[2]", "Bearer "+jmb_token[2])
					jmb_bearer_token_gid := "Bearer " + jmb_token[2]
					req_1.Header.Add("Authorization", jmb_bearer_token_gid)
					req_1.Header.Add("Content-Type", c_type)
					resp_1, _ := http.DefaultClient.Do(req_1)
					defer resp_1.Body.Close()
					fmt.Println("resp_1", resp_1)
					bodynew_1, _ := ioutil.ReadAll(resp_1.Body)
					fmt.Println("RId has failed and we are in GID", string(bodynew_1))
					fmt.Fprintf(w, "%s", bodynew_1)
				}else if resp.StatusCode != 200 {

					fmt.Println("here status is ",resp.StatusCode)
					fmt.Fprintf(w, "%s", bodynew)
				}else {
					fmt.Println("came into else block of if else in status code ",resp.StatusCode)
				}

the problem is my Json body will always be dynamic , the values keeps changing so my json structure should also change . is there a simple way like in java where i can send the body as it is to the next step

  1. Can you try to format your code correctly so I can read it, or post it in a github gist? It is very hard to follow as is.

  2. You could try using a map[string]interface{} if all else fails, but there are some downsides to this approach.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.