...

Source file src/github.com/henvic/httpretty/example/httprepl/main.go

Documentation: github.com/henvic/httpretty/example/httprepl

     1  package main
     2  
     3  import (
     4  	"bufio"
     5  	"fmt"
     6  	"net/http"
     7  	"net/url"
     8  	"os"
     9  	"runtime"
    10  	"strings"
    11  
    12  	"github.com/henvic/httpretty"
    13  )
    14  
    15  func main() {
    16  	logger := &httpretty.Logger{
    17  		Time:           true,
    18  		TLS:            true,
    19  		RequestHeader:  true,
    20  		RequestBody:    true,
    21  		ResponseHeader: true,
    22  		ResponseBody:   true,
    23  		Colors:         true, // erase line if you don't like colors
    24  		Formatters:     []httpretty.Formatter{&httpretty.JSONFormatter{}},
    25  	}
    26  
    27  	client := &http.Client{
    28  		Transport: logger.RoundTripper(http.DefaultTransport),
    29  	}
    30  
    31  	fmt.Print("httprepl is a small HTTP client REPL (read-eval-print-loop) program example\n\n")
    32  	help()
    33  
    34  	reader := bufio.NewReader(os.Stdin)
    35  	for {
    36  		fmt.Print("$ ")
    37  		readEvalPrint(reader, client)
    38  	}
    39  }
    40  
    41  func readEvalPrint(reader *bufio.Reader, client *http.Client) {
    42  	s, err := reader.ReadString('\n')
    43  
    44  	if err != nil {
    45  		fmt.Fprintf(os.Stderr, "cannot read stdin: %v\n", err)
    46  		os.Exit(1)
    47  	}
    48  
    49  	if runtime.GOOS == "windows" {
    50  		s = strings.TrimRight(s, "\r\n")
    51  	} else {
    52  		s = strings.TrimRight(s, "\n")
    53  	}
    54  
    55  	s = strings.TrimSpace(s)
    56  
    57  	switch {
    58  	case s == "exit":
    59  		os.Exit(0)
    60  	case s == "help":
    61  		help()
    62  		return
    63  	case s == "":
    64  		return
    65  	case s == "get":
    66  		fmt.Fprintln(os.Stderr, "missing address")
    67  	case !strings.HasPrefix(s, "get "):
    68  		fmt.Fprint(os.Stderr, "invalid command\n\n")
    69  		return
    70  	}
    71  
    72  	s = strings.TrimPrefix(s, "get ")
    73  	uri, err := url.Parse(s)
    74  
    75  	if err == nil && uri.Scheme == "" {
    76  		uri.Scheme = "http"
    77  		s = uri.String()
    78  	}
    79  
    80  	// we just ignore the request contents but you can see it printed thanks to the logger.
    81  	if _, err := client.Get(s); err != nil {
    82  		fmt.Fprintf(os.Stderr, "%+v\n\n", err)
    83  	}
    84  
    85  	fmt.Println()
    86  }
    87  
    88  func help() {
    89  	fmt.Print(`Commands available:
    90  get <address>	URL to get. Example: "get www.google.com"
    91  help		This command list
    92  exit		Quit the application
    93  
    94  `)
    95  }
    96  

View as plain text