summaryrefslogtreecommitdiff
path: root/doc/codelab/wiki/get.go
blob: 383935378db3d0d6fa11e371d9cb53bb79d3df0f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main

import (
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"os"
	"strings"
)

var (
	post = flag.String("post", "", "urlencoded form data to POST")
	addr = flag.Bool("addr", false, "find open address and print to stdout")
)

func main() {
	flag.Parse()
	if *addr {
		l, err := net.Listen("tcp", "127.0.0.1:0")
		if err != nil {
			log.Fatal(err)
		}
		defer l.Close()
		fmt.Print(l.Addr())
		return
	}
	url := flag.Arg(0)
	if url == "" {
		log.Fatal("no url supplied")
	}
	var r *http.Response
	var err error
	if *post != "" {
		b := strings.NewReader(*post)
		r, err = http.Post(url, "application/x-www-form-urlencoded", b)
	} else {
		r, err = http.Get(url)
	}
	if err != nil {
		log.Fatal(err)
	}
	defer r.Body.Close()
	_, err = io.Copy(os.Stdout, r.Body)
	if err != nil {
		log.Fatal(err)
	}
}