官术网_书友最值得收藏!

How to do it…

In this recipe, we will create a simple HTML form that has two input fields and a button to submit the form. Perform the following steps:

  1. Create login-form.html inside the templates directory, as follows:
$ mkdir templates && cd templates && touch login-form.html
  1. Copy the following content to login-form.html:
<html>
<head>
<title>First Form</title>
</head>
<body>
<h1>Login</h1>
<form method="post" action="/login">
<label for="username">Username</label>
<input type="text" id="username" name="username">
<label for="password">Password</label>
<input type="password" id="password" name="password">
<button type="submit">Login</button>
</form>
</body>
</html>

The preceding template has two textboxes—username and password—along with a Login button.

On clicking the Login button, the client will make a POST call to an action defined in an HTML form, which is /login in our case.

  1. Create html-form.go, where we will parse the form template and write it onto an HTTP response stream, as follows:
package main
import
(
"html/template"
"log"
"net/http"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
func login(w http.ResponseWriter, r *http.Request)
{
parsedTemplate, _ := template.ParseFiles("templates/
login-form.html")
parsedTemplate.Execute(w, nil)
}
func main()
{
http.HandleFunc("/", login)
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil)
if err != nil
{
log.Fatal("error starting http server : ", err)
return
}
}

With everything in place, the directory structure should look like the following:

  1. Run the program with the following command:
$ go run html-form.go
主站蜘蛛池模板: 当涂县| 巫山县| 明水县| 海伦市| 南陵县| 高碑店市| 高台县| 新邵县| 太仆寺旗| 靖边县| 阳信县| 西乡县| 盐池县| 兴安盟| 民县| 修武县| 望城县| 林周县| 临西县| 彰化市| 偏关县| 青岛市| 衡南县| 福建省| 林州市| 遂溪县| 成武县| 辽阳市| 楚雄市| 定远县| 西藏| 庆城县| 南阳市| 台东市| 阿图什市| 泽普县| 宜兴市| 顺平县| 团风县| 乌兰察布市| 盐池县|