PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 18, 2022

[FIXED] How te send a POST with both URL parameters and a JSON body?

 July 18, 2022     document-body, go, http, post, url-parameters     No comments   

Issue

I found how to send a POST with URL parameters, or how to send a POST with a JSON body, but I do not know how to combine them together (a request with both a URL with parameters, and a JSON body).

The code below (which is not correct) shows the commbination I am looking for. I can use either bytes.NewBuffer(jsonStr) or strings.NewReader(parm.Encode()) but not both.

package main

import (
    "bytes"
    "net/http"
    "net/url"
    "strings"
)

func main() {
    var jsonStr = []byte(`{"title":"my request"}`)
    parm := url.Values{}
    parm.Add("token", "hello")
    req, err := http.NewRequest("POST", "https://postman-echo.com/post", bytes.NewBuffer(jsonStr), strings.NewReader(parm.Encode()))
    if err != nil {
        panic(err)
    }
    req.Header.Set("Content-Type", "application/json")
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

}

How to build a full POST call with all the components?


Solution

Use the only json as your request body, and apply the URL parameters like this:

req.URL.RawQuery = parm.Encode()

From Go doing a GET request and building the Querystring



Answered By - Hymns For Disco
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing