欢迎,来自IP地址为:216.73.216.144 的朋友

之前使用Go语言开发的web服务器过于简单,只能根据用户请求的url来显示相应内容。现在将要把这个web服务器的功能进一步扩展,就是可以处理用户表单。
我们首先在代码中构建一个用户表单,然后通过对应的处理函数将此表单发送给浏览器,并接收用户的输入内容,最后在浏览器中显示出来。接收用户输入时,会有GET和POST的区别。当使用GET方法时,浏览器中会完整显示请求的全部内容,即url会包含形如”?parament=value”的内容来将参数和对应数值传递给服务器。
示例代码如下:
package main
import (
"net/http"
"io"
"log"
)
const form = `<html><body><form action="#" method="post" name="bar">
<input type="text" name="in"/><br>
<input type="text" name="confirm"/><br>
<input type="submit" value="Submit"/>
</form></body></html>`
func SimpleServer(w http.ResponseWriter, req *http.Request){
io.WriteString(w,"<h1>Hello World !</h1>" + req.URL.Path[1:])
}
func FormServer(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-type","text/html")
switch req.Method {
case "GET":
io.WriteString(w,form)
case "POST":
io.WriteString(w,req.FormValue("in"))
io.WriteString(w,req.FormValue("confirm"))
}
}
func main() {
http.HandleFunc("/", SimpleServer)
http.HandleFunc("/form",FormServer)
err := http.ListenAndServe("localhost:8080",nil)
if err != nil{
log.Fatal("ListenAndServe: ",err.Error())
}
}
执行上面的代码启动web服务器后,可以通过不同的url来区分显示内容,如果直接输入”http://localhost:8080/form?in=daehub”,会被强制转为用户表单页面;输入表单并提交后,会将内容显示出来。
