- 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
推薦閱讀
- 5G承載網網絡規劃與組網設計
- 社交電商運營策略、技巧與實操
- JBoss EAP6 High Availability
- WordPress Web Application Development
- 高級網絡技術
- 物聯網工程導論(第3版)
- AIoT應用開發與實踐
- LwIP應用開發實戰指南:基于STM32
- Hands-On Docker for Microservices with Python
- Building RESTful Web Services with .NET Core
- 算力網絡:云網融合2.0時代的網絡架構與關鍵技術
- 互聯網安全的40個智慧洞見(2018)
- 萬物互聯:物聯網核心技術與安全
- 企業網絡組建與維護項目式教程
- Advanced Node.js Development