robust_webserver.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // robust_webserver.go
  2. package main
  3. import (
  4. "net/http"
  5. "io"
  6. "log"
  7. )
  8. const form = `<html><body><form action="#" method="post" name="bar">
  9. <input type="text" name="in"/>
  10. <input type="submit" value="Submit"/>
  11. </form></html></body>`
  12. type HandleFnc func(http.ResponseWriter, *http.Request)
  13. /* handle a simple get request */
  14. func SimpleServer(w http.ResponseWriter, request *http.Request) {
  15. io.WriteString(w, "<h1>hello, world</h1>")
  16. }
  17. /* handle a form, both the GET which displays the form
  18. and the POST which processes it.*/
  19. func FormServer(w http.ResponseWriter, request *http.Request) {
  20. w.Header().Set("Content-Type", "text/html")
  21. switch request.Method {
  22. case "GET":
  23. /* display the form to the user */
  24. io.WriteString(w, form)
  25. case "POST":
  26. /* handle the form data, note that ParseForm must
  27. be called before we can extract form data*/
  28. //request.ParseForm();
  29. //io.WriteString(w, request.Form["in"][0])
  30. io.WriteString(w, request.FormValue("in"))
  31. }
  32. }
  33. func main() {
  34. http.HandleFunc("/test1", logPanics(SimpleServer))
  35. http.HandleFunc("/test2", logPanics(FormServer))
  36. if err := http.ListenAndServe(":8088", nil); err != nil {
  37. panic(err)
  38. }
  39. }
  40. func logPanics(function HandleFnc) HandleFnc {
  41. return func(writer http.ResponseWriter, request *http.Request) {
  42. defer func() {
  43. if x := recover(); x != nil {
  44. log.Printf("[%v] caught panic: %v", request.RemoteAddr, x)
  45. }
  46. }()
  47. function(writer, request)
  48. }
  49. }