Building HTTP Clients that interact with a variety of security tools and resources.
Basic Preparation:
Go's net/HTTP standard package contains several convenience functions to quickly and easily send POST, GET, and HEAD requests, which are arguably the most common HTTP verbs you'll use.
Get(url string) (resp *Response, err error) Head(url string) (resp *Response, err error) Post(url string, bodyType string, body io.Reader) (resp *Response, err error)
Additional POST request, called PostForm()
func POSTFORM(url string, data url.Values) (resp *Response, err error)
No convenience functions exist for other HTTP verbs, such as PATCH, PUT, or DELETE. Use these verbs to interact with RESTful APIs.
Generate a Request using the NewRequest() function.
func NewRequest(methond, url string, body io.Reader) (resp *Response, err error)
Uses the ioutil.ReadAll() function to read data from the response body.
package main import ( "fmt" "io/ioutil" "log" "net/http" ) func main() { resp, err := http.Get("http://www.bing.com/robots.txt") if err != nil { log.Panicln(err) } // Print HTTP Status fmt.Println(resp.Status) //Read and display response body body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Panicln(err) } fmt.Println(string(body)) resp.Body.Close() }
Structured Response Parsing
JSON file
{"Message": "All is good with the world","Status": "Success"}
Go Parsing codes
package main import ( "encoding/json" "log" "net/http" ) type Status struct { Message string Status string } func main() { res, err := http.Post( "http://IP:PORT/ping", "application/json", nil, ) if err != nil { log.Fatalln(err) } var status Status if err := json.NewDecoder(res.Body).Decode(&status); err != nil { log.Fatalln(err) } defer res.Body.Close() log.Printf("%s -> %s ", status.Status, status.Message) }