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

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httputil"
	"time"

	"github.com/fatih/color"
)

func showRequestBody(req *http.Request) {
	showTimestamp()

	if !globalOptions.NoColour {
		color.Set(color.FgBlue)
	}

	body, _ := ioutil.ReadAll(req.Body)
	fmt.Println(string(body[:]))
}

func showResponseBody(rsp *http.Response) {
	showTimestamp()

	if !globalOptions.NoColour {
		color.Set(color.FgRed)
	}

	body, _ := ioutil.ReadAll(rsp.Body)
	fmt.Println(string(body[:]))

	color.Unset()
}

func showRequestHeaders(req *http.Request) {
	showTimestamp()

	if !globalOptions.NoColour {
		color.Set(color.FgBlue)
	}

	// show request line
	fmt.Println(req.Method + " " + req.URL.Path + " " + req.Proto)

	// show headers
	for k := range req.Header {
		fmt.Println(k + ": " + req.Header[k][0])
	}

	color.Unset()
}

func showResponseHeaders(rsp *http.Response) {
	showTimestamp()

	if !globalOptions.NoColour {
		color.Set(color.FgRed)
	}

	// show status line
	fmt.Println(rsp.Proto + " " + rsp.Status)

	// show headers
	for k := range rsp.Header {
		fmt.Println(k + ": " + rsp.Header[k][0])
	}

	color.Unset()
}

func showEntireRequest(req *http.Request) {
	showTimestamp()

	if !globalOptions.NoColour {
		color.Set(color.FgBlue)
	}

	dump, _ := httputil.DumpRequest(req, true)
	fmt.Println(string(dump[:]))

	color.Unset()
}

func showEntireResponse(rsp *http.Response) {
	showTimestamp()

	if !globalOptions.NoColour {
		color.Set(color.FgRed)
	}

	dumpRsp, _ := httputil.DumpResponse(rsp, true)
	fmt.Println(string(dumpRsp[:]))

	color.Unset()
}

func showTimestamp() {
	if !globalOptions.NoTimestamps {
		fmt.Println(time.Now().Format(time.StampMilli))
	}
}