GO web中简单的表单应用
程序员文章站
2022-07-03 23:20:14
...
package main
import (
"fmt"
"net/http"
"strings"
)
func sayHello(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
fmt.Fprint(w, "<html><head><title></title></head><body><form action='http://127.0.0.1:9090/login' method='post'>用户名:<input type='text' name='username'>密码:<input type='password' name='password'><input type='submit' value='登陆'></form></body></html>")
return
}
http.NotFound(w, r)
}
func login(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //解释表格参数
for k, v := range r.Form { //遍历表格数据
fmt.Println("key:", k)
fmt.Println("value:", strings.Join(v, ""))//strings.Join(v, "|")把字符串数组v中字符串拼成一个完整的字符,使用“|”隔开,例如var s=[]string{"壹","贰","叁"},strings.Join(s, "")结果是:壹|贰|叁
}
fmt.Fprint(w, "login OK!") //将内容输出到客户端
}
func main() {
http.HandleFunc("/login", login)//设置访问的路由
http.HandleFunc("/", sayHello)
http.ListenAndServe(":9090", nil)//设置监听端口
}
在浏览器中输入地址:localhost:9090,前端输出内容:
点击登录后跳转