Skip to content

Instantly share code, notes, and snippets.

@davidlares
Last active July 14, 2021 00:44
Show Gist options
  • Save davidlares/a253a6c47054ca1de924478764a209d7 to your computer and use it in GitHub Desktop.
Save davidlares/a253a6c47054ca1de924478764a209d7 to your computer and use it in GitHub Desktop.
Raw HTTP packet digest with Golang
package main
import (
"io/ioutil"
"net/http"
"strings"
"fmt"
"log"
)
func main() {
// GET request
http.HandleFunc("/", getHandler)
// POST request
http.HandleFunc("/data", postHandler)
// Server
http.ListenAndServe(":9000", nil)
}
func getHandler(w http.ResponseWriter, r *http.Request) {
// HTTP Version
proto := r.Proto
fmt.Fprintln(w, "Proto: ", proto)
// Method
method := r.Method
fmt.Fprintln(w, "Method: ", method)
// Showing the URI
requestURI := r.RequestURI
fmt.Fprintln(w, "Request URI: ", requestURI)
// The complete URL
url := r.URL
//URL Has parts
fmt.Fprintln(w, "URL: ", url.String())
fmt.Fprintln(w, "URL Scheme: ", url.Scheme)
fmt.Fprintln(w, "URL Host: ", url.Host)
fmt.Fprintln(w, "URL Path: ", url.Path)
fmt.Fprintln(w, "URL RawQuery: ", url.RawQuery)
fmt.Fprintln(w, "URL Fragment: ", url.Fragment)
// Hostname and Port
hostname := url.Hostname()
port := url.Port()
fmt.Fprintln(w, "Hostname: ", hostname, ", Port: ", port)
// Handling query params (map)
queryValues := url.Query()
fmt.Fprintln(w, "Query Values: ")
// Iterating
for key, val := range queryValues {
fmt.Fprintln(w, key+": "+strings.Join(val, ","))
}
// Headers
headers := ""
for k, v := range r.Header {
headers += k + "=" + strings.Join(v, ",") + "\n"
}
// Printing headers
fmt.Fprintln(w, "Headers: \n"+headers)
// Custom-Header
myHeader := r.Header.Get("Custom-Header")
fmt.Fprintln(w, "Custom-Header: "+myHeader)
// Another headers
fmt.Fprintln(w, "Referer: "+r.Referer()) //Refering URL
fmt.Fprintln(w, "UserAgent: "+r.UserAgent()) //Client
// Remote address
remoteAddress := r.RemoteAddr
fmt.Fprintln(w, "Remote Address: "+remoteAddress)
// Body
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println("Error Reading Body")
}
// converting body in string
fmt.Fprintln(w, "Body: ", string(body))
}
func postHandler(w http.ResponseWriter, r *http.Request) {
//First we need to call ParseForm
err := r.ParseForm()
if err != nil {
fmt.Fprintf(w, "Error with form")
}
// method
method := r.Method
fmt.Fprintln(w, "Method: ", method)
// Request URI
requestURI := r.RequestURI
fmt.Fprintln(w, "Request URI: ", requestURI)
//Post and Patch values And Also Querystring
for key, val := range r.Form {
fmt.Fprintln(w, key, ": ", strings.Join(val, ","))
}
// Get an individual value from form
custom := r.Form.Get("Custom-value")
fmt.Fprintln(w, "Custom-value: "+ custom)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment