15.4 写一个简单的网页应用

下边的程序在端口8088上启动了一个网页服务器;SimpleServer会处理/test1url使它在浏览器输出hello worldFormServer会处理/test2url:如果url最初由浏览器请求,那么它就是一个GET请求,并且返回一个form常量,包含了简单的input表单,这个表单里有一个文本框和一个提交按钮。当在文本框输入一些东西并点击提交按钮的时候,会发起一个POST请求。FormServer中的代码用到了switch来区分两种情况。在POST情况下,使用request.FormValue("inp")通过文本框的name属性inp来获取内容,并写回浏览器页面。在控制台启动程序并在浏览器中打开urlhttp://localhost:8088/test2来测试这个程序:

示例 15.10 simple_webserver.go

  1. package main
  2. import (
  3. "io"
  4. "net/http"
  5. )
  6. const form = `
  7. <html><body>
  8. <form action="#" method="post" name="bar">
  9. <input type="text" name="in" />
  10. <input type="submit" value="submit"/>
  11. </form>
  12. </body></html>
  13. `
  14. /* handle a simple get request */
  15. func SimpleServer(w http.ResponseWriter, request *http.Request) {
  16. io.WriteString(w, "<h1>hello, world</h1>")
  17. }
  18. func FormServer(w http.ResponseWriter, request *http.Request) {
  19. w.Header().Set("Content-Type", "text/html")
  20. switch request.Method {
  21. case "GET":
  22. /* display the form to the user */
  23. io.WriteString(w, form)
  24. case "POST":
  25. /* handle the form data, note that ParseForm must
  26. be called before we can extract form data */
  27. //request.ParseForm();
  28. //io.WriteString(w, request.Form["in"][0])
  29. io.WriteString(w, request.FormValue("in"))
  30. }
  31. }
  32. func main() {
  33. http.HandleFunc("/test1", SimpleServer)
  34. http.HandleFunc("/test2", FormServer)
  35. if err := http.ListenAndServe(":8088", nil); err != nil {
  36. panic(err)
  37. }
  38. }

注:当使用字符串常量表示html文本的时候,包含<html><body></body></html>对于让浏览器识别它收到了一个html非常重要。

更安全的做法是在处理器中使用w.Header().Set("Content-Type", "text/html")在写入返回之前将headercontent-type设置为text/html

content-type会让浏览器认为它可以使用函数http.DetectContentType([]byte(form))来处理收到的数据

练习 15.6 [statistics.go]

编写一个网页程序,可以让用户输入一连串的数字,然后将它们打印出来,计算出这些数字的均值和中值,就像下边这张截图一样:

15.4 写一个简单的网页应用 - 图1