Skip to content

Instantly share code, notes, and snippets.

@zeddee
Created August 10, 2018 17:01
Show Gist options
  • Select an option

  • Save zeddee/a3ab08354145007869e07217caba8692 to your computer and use it in GitHub Desktop.

Select an option

Save zeddee/a3ab08354145007869e07217caba8692 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
func request1(url string) string {
res, err := http.Get(url)
if err != nil {
log.Println(err)
}
var data []byte
data, err = ioutil.ReadAll(res.Body)
return string(data)
}
func post1(url string, jsonValue []byte) string {
var (
data []byte
res *http.Response
err error
)
res, err = http.Post(url, "application/json", bytes.NewBuffer(jsonValue))
if err != nil {
log.Fatal(err)
}
data, err = ioutil.ReadAll(res.Body)
return string(data)
}
func reqClient(url string, jsonValue []byte) string {
var (
req *http.Request
res *http.Response
data []byte
err error
)
client := &http.Client{}
req, err = http.NewRequest("POST", url, bytes.NewBuffer(jsonValue))
if err != nil {
log.Println(err)
}
req.Header.Set("Content-Type", "application/json")
res, err = client.Do(req)
if err != nil {
log.Println(err)
}
data, err = ioutil.ReadAll(res.Body)
if err != nil {
log.Println(err)
}
return string(data)
}
func main() {
jsonData := map[string]string{"firstname": "Nic", "lastname": "Raboy"}
jsonValue, err := json.Marshal(jsonData)
if err != nil {
log.Println(err)
}
fmt.Println("Starting the application…")
fmt.Println(request1("https://httpbin.org/ip"))
fmt.Println(post1("https://httpbin.org/post", jsonValue))
// using http.Client for control over:
// - client headers
// - redirect policy
// - other settings
fmt.Println(reqClient("https://httpbin.org/post", jsonValue))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment