1
0
mirror of https://github.com/golang/go synced 2024-11-20 03:54:40 -07:00
go/doc/codelab/wiki/get.go
Andrew Gerrand 5899cab037 doc/codelab/wiki: tests use available TCP port
R=bradfitz, dsymonds, r2, dangabrad, rsc
CC=golang-dev
https://golang.org/cl/4043043
2011-01-27 23:19:37 +10:00

51 lines
825 B
Go

package main
import (
"http"
"flag"
"fmt"
"io"
"log"
"net"
"os"
"strings"
)
var (
post = flag.String("post", "", "urlencoded form data to POST")
port = flag.Bool("port", false, "find open port and print to stdout")
)
func main() {
flag.Parse()
if *port {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
log.Exit(err)
}
defer l.Close()
fmt.Print(l.Addr().(*net.TCPAddr).Port)
return
}
url := flag.Arg(0)
if url == "" {
log.Exit("no url supplied")
}
var r *http.Response
var err os.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.Exit(err)
}
defer r.Body.Close()
_, err = io.Copy(os.Stdout, r.Body)
if err != nil {
log.Exit(err)
}
}