Contact Form Example in Go

In this topic, I’m going to make a simple contact form in Go.

Table of Contents

  1. Create Contact Form
  2. Parse Form & Handle Submit
  3. Run & Test

Create Contact Form

In the root folder of your project, create a simple HTML contact form named contact.html:

contact.html
{{if .Success}}
<p>Your message has been sent!</p>
{{else}}
<p>Contact</p>
<form action="/contact" method="POST">
    <label>Name:</label><br />
    <input type="text" name="name"><br />
    <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 /><br />
    <input type="submit">
</form>
{{end}}

Parse Form & Handle Submit

Create a file called contact.go and paste this code:

contact.go
package main

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

type ContactDetails struct {
    Name    string
    Email   string
    Subject string
    Message string
}

func main() {
    tmpl, err := template.ParseFiles("contact.html")
    if err != nil {
        log.Fatal("Parse: ", err)
        return
    }

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

        // get form data
        formData := ContactDetails{
            Name:   r.FormValue("name"),
            Email:   r.FormValue("email"),
            Subject: r.FormValue("subject"),
            Message: r.FormValue("message"),
        }

        // do something with the submitted form data
        fmt.Printf("%+v\n", formData)

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

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

Run & Test

We’ve created /contact route to display and handle the form.Now run the project using command:

go run contact.go

We’ve opened port 80. So, visit localhost/contact to see the form. You can enter details and hit the submit button to see success message. To see the contact details please take a look at the console after hitting the submit button.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.