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

  • Go Web Development Cookbook
  • Arpit Aggarwal
  • 183字
  • 2021-08-27 19:01:18

How to do it…

  1. Install the github.com/gorilla/schema package using the go get command, as follows:
$ go get github.com/gorilla/schema
  1. 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
}
}
  1. Run the program with the following command:
$ go run html-form-read.go
主站蜘蛛池模板: 新竹县| 湖州市| 县级市| 左云县| 成都市| 沅江市| 松阳县| 永登县| 南雄市| 九台市| 西宁市| 夏津县| 疏附县| 武宁县| 兰州市| 峡江县| 佛山市| 屯昌县| 五寨县| 奉化市| 云安县| 化隆| 华安县| 云南省| 伊宁县| 新龙县| 固原市| 股票| 辽中县| 湘阴县| 荥经县| 当涂县| 七台河市| 南昌县| 黎川县| 黑山县| 翁牛特旗| 辽阳县| 道孚县| 诏安县| 金山区|