post image January 6, 2022 | 1 min Read

Go r.Body.Read()

package main

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

var tpl *template.Template

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


func main()  {
	http.HandleFunc("/", foo)
	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.ListenAndServe(":8080", nil)
	
}

// Options for <form> and POST method in particular
// 	- <form method="POST" enctype="multipart/form-data">
// 	- <form method="POST" enctype="multipart/x-www-form-urlencoded">
// 	- <form method="POST" enctype="text/plain">


func foo(w http.ResponseWriter, r *http.Request)  {
	bs := make([]byte, r.ContentLength)
	r.Body.Read(bs)
	body := string(bs)


	err := tpl.ExecuteTemplate(w, "index.gohtml", body)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		log.Fatalln(err)
	}
}

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


// <form method="POST" enctype="text/plain">
//     <label for="idx-f">Choose File To Upload</label>
//     <input type="file" id="idx-f" name="q">
    
//     <label for="idx-f">First Name</label>
//     <input type="text" id="idx-f" name="first"><br>
//     <label for="idx-f">Last Name</label>
//     <input type="text" id="idx-l" name="last"> <br>
//     <label for="idx-f">Subscribed</label>
//     <input type="checkbox" id="idx-s" name="sub"><br>


//     <br>
//     <input type="submit">
// </form>

// {{if .}}
// <h1>Here are the body content</h1>
// {{.}}
// {{end}}
// </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