Golang: Simultaneous function Calls for http post request - http

I need to call multiple URL at the same time. My functions get called at the same time (in milli seconds) but the moment I add a Http post request to the code it gets called one after the other. Below is the code:
Check(url1)
Check(url2)
func Check(xurl string) {
nowstartx := time.Now()
startnanos := nowstartx.UnixNano()
nowstart := startnanos / 1000000
fmt.Println(nowstart)
json = {"name" : "test"}
req, err := http.NewRequest("POST", xurl, bytes.NewBuffer(json))
req.Header.Set("X-Custom-Header", "myvalue")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
} else {
defer resp.Body.Close()
body, _ = ioutil.ReadAll(resp.Body)
}
}
Appreciate help, I need to get the same time (in milliseconds) when I run the program.

This is achieved by using Goroutines
go Check(url1)
go Check(url2)
func Check(xurl string) {
nowstartx := time.Now()
startnanos := nowstartx.UnixNano()
nowstart := startnanos / 1000000
fmt.Println(nowstart)
json = {"name" : "test"}
req, err := http.NewRequest("POST", xurl, bytes.NewBuffer(json))
req.Header.Set("X-Custom-Header", "myvalue")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
} else {
defer resp.Body.Close()
body, _ = ioutil.ReadAll(resp.Body)
}
}

Related

Unable to read entire response body

I'm trying to make a straightforward request to an API, which works just fine in Postman, and weirdly occasionally works in my app, but usually fails when trying to parse the JSON because only about half the response is being read into the body variable. When the entire response is read everything works fine. I'm not really sure what if anything I'm doing wrong here, or if there's anything else I can do differently to make sure that the entire response is parsed.
var reqBody = []byte(fmt.Sprintf(`{
"methodName": "GetPropertyList",
"params": {
"token_key": "%v",
"token_secret": "%v"
}
}`, token, secret))
req, err := http.NewRequest("POST", proxy_url, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Printf("Couldn't get property field list: %v")
} else {
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
bodyStr := string(body)
log.Printf("BODY: %v", len(bodyStr))
var respModel ResponseModel
err = json.Unmarshal(body, &respModel) //Error happens here
}
you can do it by using json.NewDecoder(resp.Body).Decode(&respModel)
The full code would then look like:
var token, secret, proxy_url string
var reqBody = []byte(fmt.Sprintf(`{
"methodName": "GetPropertyList",
"params": {
"token_key": "%v",
"token_secret": "%v"
}
}`, token, secret))
req, err := http.NewRequest("POST", proxy_url, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := http.Client{}
var respModel ResponseModel
resp, err := client.Do(req)
if err != nil {
log.Printf("Couldn't get property field list: %v", err)
} else {
err := json.NewDecoder(resp.Body).Decode(&respModel)
}

Convert string from args/flags to json then send to post http request as body

I'm trying to pass the values ​​I get in the arg / flag --BODY="{user: root}" as the body of the post request I'm trying to do, I've already used json.Marshal and even so I wasn't successful, thanks for the help !
Code below:
func Custom(method string, url string, token string, data string) {
req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
req.Header.Add("Authorization", FormatBearerToken(token))
// req.Header.Set("Content-Type", "application/json")
if err != nil {
log.Println("Request failed, ", err)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println(err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
log.Println("response Body:", string(body))
}

How to send post form data through a http client?

I have a problem with post request, needed to send simple form data through http client.
http.PostForm() is not ok because I need to set my own user agent and other headers.
Here is the sample
func main() {
formData := url.Values{
"form1": {"value1"},
"form2": {"value2"},
}
client := &http.Client{}
//Not working, the post data is not a form
req, err := http.NewRequest("POST", "http://test.local/api.php", strings.NewReader(formData.Encode()))
if err != nil {
log.Fatalln(err)
}
req.Header.Set("User-Agent", "Golang_Super_Bot/0.1")
resp, err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
log.Println(string(body))
}
You also need to set the content type to application/x-www-form-urlencoded which corresponds to the encoding used by Value.Encode().
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
This is mentioned as one of the things done by Client.PostForm.

How can I upload a file to server, without browser, using go?

trsp := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
Url := "https://127.0.0.1:8080"
client := &http.Client{Transport: trsp}
request, _ := http.NewRequest("POST", Url, nil)
k, _ := os.Open(nameOfFile)
request.Header.Set("Action", "download"+k.Name())
...
...
client.Do(request)
I have server, and I need to upload to server a file. What should I do with request? As I think I shoud write into request.Body and then, from server handle this query
you need use the "mime/multipart"package to make the http body. like this.
http://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/
func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, filepath.Base(path))
if err != nil {
return nil, err
}
_, err = io.Copy(part, file)
for key, val := range params {
_ = writer.WriteField(key, val)
}
err = writer.Close()
if err != nil {
return nil, err
}
return http.NewRequest("POST", uri, body)
}

How to set headers in http get request?

I'm doing a simple http GET in Go:
client := &http.Client{}
req, _ := http.NewRequest("GET", url, nil)
res, _ := client.Do(req)
But I can't found a way to customize the request header in the doc, thanks
The Header field of the Request is public. You may do this :
req.Header.Set("name", "value")
Pay attention that in http.Request header "Host" can not be set via Set method
req.Header.Set("Host", "domain.tld")
but can be set directly:
req.Host = "domain.tld":
req, err := http.NewRequest("GET", "http://10.0.0.1/", nil)
if err != nil {
...
}
req.Host = "domain.tld"
client := &http.Client{}
resp, err := client.Do(req)
If you want to set more than one header, this can be handy rather than writing set statements.
client := http.Client{}
req , err := http.NewRequest("GET", url, nil)
if err != nil {
//Handle Error
}
req.Header = http.Header{
"Host": {"www.host.com"},
"Content-Type": {"application/json"},
"Authorization": {"Bearer Token"},
}
res , err := client.Do(req)
if err != nil {
//Handle Error
}
Go's net/http package has many functions that deal with headers. Among them are Add, Del, Get and Set methods. The way to use Set is:
func yourHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("header_name", "header_value")
}

Resources