- Go Web Development Cookbook
- Arpit Aggarwal
- 183字
- 2021-08-27 19:01:18
How to do it…
- Install the github.com/gorilla/schema package using the go get command, as follows:
$ go get github.com/gorilla/schema
- Create html-form-read.go, where we will read an HTML form field after decoding it using the github.com/gorilla/schema package and write Hello followed by the username to an HTTP response stream, as follows:
package main
import
(
"fmt"
"html/template"
"log"
"net/http"
"github.com/gorilla/schema"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
type User struct
{
Username string
Password string
}
func readForm(r *http.Request) *User
{
r.ParseForm()
user := new(User)
decoder := schema.NewDecoder()
decodeErr := decoder.Decode(user, r.PostForm)
if decodeErr != nil
{
log.Printf("error mapping parsed form data to struct : ",
decodeErr)
}
return user
}
func login(w http.ResponseWriter, r *http.Request)
{
if r.Method == "GET"
{
parsedTemplate, _ := template.ParseFiles("templates/
login-form.html")
parsedTemplate.Execute(w, nil)
}
else
{
user := readForm(r)
fmt.Fprintf(w, "Hello "+user.Username+"!")
}
}
func main()
{
http.HandleFunc("/", login)
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil)
if err != nil
{
log.Fatal("error starting http server : ", err)
return
}
}
- Run the program with the following command:
$ go run html-form-read.go
推薦閱讀
- 通信網(wǎng)絡(luò)基礎(chǔ)與設(shè)備
- 信息通信網(wǎng)絡(luò)建設(shè)安全管理概要2
- PLC、現(xiàn)場(chǎng)總線及工業(yè)網(wǎng)絡(luò)實(shí)用技術(shù)速成
- 中小型局域網(wǎng)組建、管理與維護(hù)實(shí)戰(zhàn)
- 物聯(lián)網(wǎng)安全技術(shù)
- Learning Swift(Second Edition)
- IPv6網(wǎng)絡(luò)切片:使能千行百業(yè)新體驗(yàn)
- 面向5G-Advanced的關(guān)鍵技術(shù)
- 光纖通信系統(tǒng)與網(wǎng)絡(luò)(修訂版)
- 一本書讀懂物聯(lián)網(wǎng)
- 5G技術(shù)核心與增強(qiáng):從R15到R17
- 計(jì)算機(jī)網(wǎng)絡(luò)技術(shù)
- 物聯(lián)網(wǎng)基礎(chǔ)及應(yīng)用
- SD-WAN 架構(gòu)與技術(shù)
- 天下一家:網(wǎng)絡(luò)聯(lián)通世界(科學(xué)新導(dǎo)向叢書)