github.com/riscv/riscv-go@v0.0.0-20200123204226-124ebd6fcc8e/doc/articles/wiki/get.go (about)

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"flag"
     9  	"fmt"
    10  	"io"
    11  	"log"
    12  	"net"
    13  	"net/http"
    14  	"os"
    15  	"strings"
    16  	"time"
    17  )
    18  
    19  var (
    20  	post = flag.String("post", "", "urlencoded form data to POST")
    21  	addr = flag.Bool("addr", false, "find open address and print to stdout")
    22  	wait = flag.Duration("wait_for_port", 0, "if non-zero, the amount of time to wait for the address to become available")
    23  )
    24  
    25  func main() {
    26  	flag.Parse()
    27  	if *addr {
    28  		l, err := net.Listen("tcp", "127.0.0.1:0")
    29  		if err != nil {
    30  			log.Fatal(err)
    31  		}
    32  		defer l.Close()
    33  		fmt.Print(l.Addr())
    34  		return
    35  	}
    36  	url := flag.Arg(0)
    37  	if url == "" {
    38  		log.Fatal("no url supplied")
    39  	}
    40  	var r *http.Response
    41  	var err error
    42  	loopUntil := time.Now().Add(*wait)
    43  	for {
    44  		if *post != "" {
    45  			b := strings.NewReader(*post)
    46  			r, err = http.Post(url, "application/x-www-form-urlencoded", b)
    47  		} else {
    48  			r, err = http.Get(url)
    49  		}
    50  		if err == nil || *wait == 0 || time.Now().After(loopUntil) {
    51  			break
    52  		}
    53  		time.Sleep(100 * time.Millisecond)
    54  	}
    55  	if err != nil {
    56  		log.Fatal(err)
    57  	}
    58  	defer r.Body.Close()
    59  	_, err = io.Copy(os.Stdout, r.Body)
    60  	if err != nil {
    61  		log.Fatal(err)
    62  	}
    63  }