post image January 6, 2022 | 1 min Read

Go explore ResponseWriter and Request

package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"net/url"
)

var tpl *template.Template

func init() {
	tpl = template.Must(template.ParseFiles("index.gohtml"))
}

type pes int

func (p pes) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		log.Fatalln(err)
	}

	data := struct {
		Method         string
		URL            *url.URL
		Submissions    map[string][]string
		Header         http.Header
		Host           string
		ContentLength  int64
	}{
		Method: r.Method,
		URL: r.URL,
		Submissions: r.Form,
		Header: r.Header,
		Host: r.Host,
		ContentLength: r.ContentLength,
	}

	for k, v := range r.Header {
		fmt.Printf("[%v]: %v\n", k, v)
	}
	
	fmt.Println()

	for k, v := range r.Form {
		fmt.Printf("Form data: [%v]: %v\n", k, v)
	}

	w.Header().Set("X-Custom-Header", "this is go")
	tpl.ExecuteTemplate(w, "index.gohtml", data)

}

func main() {
	var styriPesa pes
	http.ListenAndServe(":8080", styriPesa)
}



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Input Type Submit</title>
</head>
<body>


{{if .}}
<main>
    <p><strong>variable names</strong> (identifiers) and <em>values</em>:</p>
    {{range $key, $value := .Submissions}}
            <p><strong>{{$key}}</strong></p>
            <ul>{{range $value}}<li><em>{{.}}</em></li>{{end}}</ul>
    {{end}}

    <p><strong>variable names</strong> (identifiers) and <em>values</em>:</p>
    {{range $key, $value := .Header}}
            <p><strong>{{$key}}</strong></p>
            <ul>{{range $value}}<li><em>{{.}}</em></li>{{end}}</ul>
    {{end}}
</main>
{{end}}

{{if .URL}}
    <li>{{.URL.Scheme}}</li>
    <li>{{.URL.Opaque}}</li>
    <li>{{.URL.Host}}</li>
    <li>{{.URL.Path}}</li>
    <li>{{.URL.RawPath}}</li>

{{end}}


<form action="/?fname=James&lname=Jou" method="POST">
        <input type="text" name="fname" placeholder="first name" autofocus autocomplete="off">
        <input type="submit" name="submit-btn" value="onda button">
</form>

</body>
</html>

author image

Jan Toth

I have been in DevOps related jobs for past 6 years dealing mainly with Kubernetes in AWS and on-premise as well. I spent quite a lot …

comments powered by Disqus