Go Web学习笔记--处理表单的输入
通过一个注册的示例来演示如何通过Go语言来处理表单的输入。
首先,创建一个简单的html文件,代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login" method="post"> 用户名:<input type="text" name="username"> 密码:<input type="password" name="password"> <input type="submit" value="登录"> </form> </body> </html>
然后,编写服务端代码,一个用来在客户端打印初始化信息,一个用来处理登录逻辑
package main import ( "fmt" "html/template" "log" "net/http" "strings" ) func PrintInitInfo(w http.ResponseWriter, r *http.Request) { r.ParseForm() fmt.Println(r.Form) fmt.Println("URL:", r.URL.Path) fmt.Println("scheme:", r.URL.Scheme) for k, v := range r.Form { fmt.Println("Key:", k) fmt.Println("Value:", strings.Join(v, " ")) } fmt.Fprintf(w, "This is Init Information") } func Login(w http.ResponseWriter, r *http.Request) { fmt.Println("Method:", r.Method) if r.Method == "GET" { t, _ := template.ParseFiles("./build_web/static/login.html") log.Println(t.Execute(w, nil)) } else { r.ParseForm() fmt.Println("username:", r.Form["username"]) fmt.Println("password:", r.Form["password"]) } } func main() { http.HandleFunc("/", PrintInitInfo) http.HandleFunc("/login", Login) err := http.ListenAndServe("localhost:8080", nil) if err != nil { panic(err) } }
说明:r.Form
里面包含了所有请求的参数,比如URL中query-string、POST的数据、PUT的数据,所以当你在URL中的query-string字段和POST冲突时,会保存成一个slice,里面存储了多个值
Request本身也提供了FormValue()函数来获取用户提交的参数。如r.Form["username"]也可写成r.FormValue("username")。调用r.FormValue时会自动调用r.ParseForm,所以不必提前调用。r.FormValue只会返回同名参数中的第一个,若参数不存在则返回空字符串。
分类:
Go语言学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具