Golang-Form form submission

Go provides html/templateparsing of html template files, converting the input submitted by the template files into structures and rendering them.

package main

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

type ContactDetails struct {
    
    
	Email   string
	Subject string
	Message string
}

func main() {
    
    
	tmpl := template.Must(template.ParseFiles("H:\\go\\main\\forms.html"))

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    
    
		if r.Method != http.MethodPost {
    
    
			tmpl.Execute(w, nil)
			return
		}

		details := ContactDetails{
    
    
			Email:   r.FormValue("email"),
			Subject: r.FormValue("subject"),
			Message: r.FormValue("message"),
		}

		// do something with details
		_ = details

		tmpl.Execute(w, struct {
    
    Success bool}{
    
    true})
	})

	http.ListenAndServe(":8080", nil)
}

HTML template file content:

<!DOCTYPE html>
{
   
   {if .Success}}
<h1>Thanks for your message!</h1>
{
   
   {else}}
<h1>Contact</h1>
<form method="POST">
    <label>Email:</label><br />
    <input type="text" name="email"><br />
    <label>Subject:</label><br />
    <input type="text" name="subject"><br />
    <label>Message:</label><br />
    <textarea name="message"></textarea><br />
    <input type="submit">
</form>
{
   
   {end}}

Start the project, enter the access http://8080port
insert image description here
at will, and click submit to output a successful message.
insert image description here

Guess you like

Origin blog.csdn.net/mryang125/article/details/114242032