restful-form-handling.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/emicklei/go-restful"
  5. "github.com/gorilla/schema"
  6. "io"
  7. "net/http"
  8. )
  9. // This example shows how to handle a POST of a HTML form that uses the standard x-www-form-urlencoded content-type.
  10. // It uses the gorilla web tool kit schema package to decode the form data into a struct.
  11. //
  12. // GET http://localhost:8080/profiles
  13. //
  14. type Profile struct {
  15. Name string
  16. Age int
  17. }
  18. var decoder *schema.Decoder
  19. func main() {
  20. decoder = schema.NewDecoder()
  21. ws := new(restful.WebService)
  22. ws.Route(ws.POST("/profiles").Consumes("application/x-www-form-urlencoded").To(postAdddress))
  23. ws.Route(ws.GET("/profiles").To(addresssForm))
  24. restful.Add(ws)
  25. http.ListenAndServe(":8080", nil)
  26. }
  27. func postAdddress(req *restful.Request, resp *restful.Response) {
  28. err := req.Request.ParseForm()
  29. if err != nil {
  30. resp.WriteErrorString(http.StatusBadRequest, err.Error())
  31. return
  32. }
  33. p := new(Profile)
  34. err = decoder.Decode(p, req.Request.PostForm)
  35. if err != nil {
  36. resp.WriteErrorString(http.StatusBadRequest, err.Error())
  37. return
  38. }
  39. io.WriteString(resp.ResponseWriter, fmt.Sprintf("<html><body>Name=%s, Age=%d</body></html>", p.Name, p.Age))
  40. }
  41. func addresssForm(req *restful.Request, resp *restful.Response) {
  42. io.WriteString(resp.ResponseWriter,
  43. `<html>
  44. <body>
  45. <h1>Enter Profile</h1>
  46. <form method="post">
  47. <label>Name:</label>
  48. <input type="text" name="Name"/>
  49. <label>Age:</label>
  50. <input type="text" name="Age"/>
  51. <input type="Submit" />
  52. </form>
  53. </body>
  54. </html>`)
  55. }