Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@maksadbek
Created August 27, 2015 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maksadbek/c5648f4eae8caaa7688e to your computer and use it in GitHub Desktop.
Save maksadbek/c5648f4eae8caaa7688e to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"time"
)
func sendGet() {
var c http.Client
resp, err := c.Get("http://httpbin.org/get")
if err != nil {
panic(err)
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Println(string(content))
}
func sendPost() {
resp, err := http.Post("http://httpbin.org/post", "application/json", bytes.NewBuffer([]byte(` {'a':'b'} `)))
if err != nil {
panic(err)
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Println(string(content))
}
func sendPostForm() {
resp, err := http.PostForm("http://httpbin.org/post", url.Values{"name": {"Maksadbek"},
"id": {"123"}})
if err != nil {
panic(err)
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Println(string(content))
}
func sendPostAndWrite() {
resp, err := http.Post("http://httpbin.org/post", "application/json", bytes.NewBuffer([]byte(` {'a':'b'} `)))
if err != nil {
panic(err)
}
defer resp.Body.Close()
f, err := os.Create("downloaded")
if err != nil {
panic(err)
}
defer f.Close()
r := SlowReader{Delay: 100 * time.Millisecond, R: resp.Body}
_, err = io.Copy(f, r)
if err != nil {
panic(err)
}
}
type SlowReader struct {
Delay time.Duration
R io.Reader
}
func (s SlowReader) Read(p []byte) (int, error) {
time.Sleep(s.Delay)
return s.R.Read(p[:1])
}
func main() {
sendPostForm()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment