Skip to content

Instantly share code, notes, and snippets.

@davidlares
Last active July 14, 2021 01:33
Show Gist options
  • Save davidlares/952da02daa3cd556ca5c76ee33ae1c22 to your computer and use it in GitHub Desktop.
Save davidlares/952da02daa3cd556ca5c76ee33ae1c22 to your computer and use it in GitHub Desktop.
Raw response GET Request evaluation
package main
import (
"io/ioutil"
"net/http"
"fmt"
"log"
)
func main() {
// perform GET request
resp, err := http.Get("http://127.0.0.1:9000/example")
if err != nil {
log.Fatal(err.Error())
}
// getting status code
status := resp.StatusCode
if status > 200 {
log.Fatalf("Error on Request, StatusCode: %d", status)
}
// getting the header
content_type := resp.Header.Get("Content-type")
fmt.Println("Content-type: " + content_type)
// HTTP version
proto := resp.Proto
fmt.Println("Proto: ", proto)
// Content length
length := resp.ContentLength
fmt.Printf("Content length: %d\n", length)
// body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("Error reading Body")
}
// defering body Close
defer resp.Body.Close()
// priting result
fmt.Println("Done: ", string(body))
}
package main
import (
"io/ioutil"
"net/http"
"fmt"
"log"
)
func main() {
// GET request
http.HandleFunc("/example", myHandler)
// server instance
http.ListenAndServe(":9000", nil)
}
func myHandler(w http.ResponseWriter, r *http.Request) {
//Write Status Code
w.WriteHeader(http.StatusOK)
//Writing Other Headers
header := w.Header()
header.Set("Content-Type", "application/text")
// writing text
n, err := w.Write([]byte("Hi There"))
if err != nil {
log.Fatal("Error Writing.")
}
// bytes calculation output
fmt.Fprintf(w, "The number of bytes on the last operation were: %d", n)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment