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服務,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/387891.html
標籤:java
