Home > Backend Development > Golang > How to Parse HTML Form Input in Go?

How to Parse HTML Form Input in Go?

Patricia Arquette
Release: 2024-11-23 12:59:11
Original
555 people have browsed it

How to Parse HTML Form Input in Go?

Parsing Input from HTML Forms in Go

Understanding how to parse input from HTML forms is essential when creating dynamic web applications using Go.

Imagine a scenario where you have a simple web application with a form that collects a user's name. When the form is submitted, you want your Go application to receive the submitted name and print a greeting message.

In this example, we'll utilize the Goji framework to handle form submissions:

package main

import (
    "fmt"
    "net/http"

    "github.com/zenazn/goji"
    "github.com/zenazn/goji/web"
)

func hello(c web.C, w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    name := r.PostFormValue("name")
    fmt.Fprintf(w, "Hello, %s!", name)
}

func main() {
    goji.Post("/hello", hello)
    goji.Serve()
}
Copy after login

In this code, the hello function parses the submitted form using r.ParseForm() before accessing the form value associated with the "name" field using r.PostFormValue("name").

To connect your hello.html form with the hello.go code, you need to specify the action attribute in your form to point to the URL where the hello function is defined. Assuming your hello.html looks something like this:

<form action="/hello" method="get">
    <input type="text" name="name" />
</form>
Copy after login

When the form is submitted, the browser will send a POST request to the /hello URL, which will be handled by the hello function in your Go application. The function will then parse the form data and print the greeting message based on the submitted name.

The above is the detailed content of How to Parse HTML Form Input in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template