go web、感受一下go语言的代码简洁与优雅
go实现web页面以及提交表单
go实现web开发提交表单不管是开发还是代码量还是部署来说,轻量,简便,只需要简单几行代码就可以实现一个表单提交,也不需要像Java中需要web容器。
基于现在开发来说,几乎都是前后端分离项目,我们这里使用最简单的页面提交方式,这儿返回一个页面,然后提交一个表单,感受一下go语言的简洁。
准备
需要一个登录页面(表单)
需要提交一个表单
项目目录
代码示例
登录页面
<html>
<body>
<h2>登录页</h2>
<form action="http://127.0.0.1:8080/login" method="post">
<label>用户名:<input type="text" name="name"></label>
<label>密 码: <input type="password" name="pwd"></label>
<input type="submit" value="提交"/>
</form>
</body>
</html>
后端
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
//go语言实现 http服务端
func main() {
//注册路由
http.HandleFunc("/a",sayhello)
//首页
http.HandleFunc("/index",index)
//登录
http.HandleFunc("/login",login)
//建立监听
err := http.ListenAndServe("127.0.0.1:8080",nil)
if err!=nil {
fmt.Println("网络错误")
return
}
}
func sayhello(writer http.ResponseWriter, request *http.Request) {
writer.Write([]byte("<p style='color:red;'>你好啊哈哈哈哈哈</p>"))
//fmt.Fprint(writer,"<p style='color:red;'>你好啊哈哈哈哈哈</p>")
}
//登录页
func index(writer http.ResponseWriter, request *http.Request) {
file, err := ioutil.ReadFile("/Users/pilgrim/Desktop/go/TestDemo/src/socket/http/server/html/login.html")
if err != nil {
writer.Write([]byte("服务器错误"))
return
}
writer.Write(file)
}
//提交表单
func login(writer http.ResponseWriter, request *http.Request) {
request.ParseForm()//解析
//获取表单中的数据
name := request.Form.Get("name")
pwd := request.Form.Get("pwd")
fmt.Printf("name: %s , pwd: %s ",name,pwd)
writer.Write([]byte("登录成功"))
}
启动一下main方法
我们这儿注册了2个路由,分别是
/a
字符串返回
/index
登录页返回
/login
登录提交表单
分别是以下
登录页
登录提交后
当然控制台我们使用代码打印出提交的内容
构建一个http服务是不是相当的简洁,只需要几行代码就可以架起一个http服务。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
二维码