Newer
Older
httpcat / src / client.go
/**
  Author: Mark George <mark.george@otago.ac.nz>
  License: Zero-Clause BSD License
*/

package main

import (
	"fmt"
	"net/http"
	"os"
	"strings"
)

type ClientCommand struct {
	Headers []string `short:"H" long:"header" description:"A header to add to request in the form name|value. Use multiple times for multiple headers."`
	Method  string   `short:"m" long:"method" choice:"GET" choice:"POST" choice:"PUT" choice:"DELETE" choice:"PATCH" choice:"HEAD" choice:"OPTIONS" description:"HTTP method for request." default:"GET"`
	Body    string   `short:"b" long:"body" description:"Request body to send."`
	Args    struct {
		URL string
	} `positional-args:"yes" required:"yes"`
}

func (opts *ClientCommand) Execute(args []string) error {
	sendRequest(opts)
	return nil
}

func sendRequest(opts *ClientCommand) {

	client := http.Client{}

	request, _ := http.NewRequest(opts.Method, opts.Args.URL, strings.NewReader(opts.Body))

	// add extra headers if specified
	if len(opts.Headers) > 0 {
		for _, header := range opts.Headers {
			if name, value, err := parseHeader(header); err == nil {

				if globalOptions.Verbose {
					fmt.Println("Adding request header - " + name + ": " + value)
				}

				request.Header.Add(name, value)
			} else {
				fmt.Println("The following header is not in the correct format: " + header + "\nCorrect format is: 'name|value'")
				os.Exit(1)
			}
		}
	}

	if response, err := client.Do(request); err != nil {
		fmt.Println("Could not connect to server")
	} else {
		defer response.Body.Close()
		showResponse(response)
	}

}