restful-resource-functions.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package main
  2. import (
  3. "github.com/emicklei/go-restful"
  4. "log"
  5. "net/http"
  6. )
  7. // This example shows how to use methods as RouteFunctions for WebServices.
  8. // The ProductResource has a Register() method that creates and initializes
  9. // a WebService to expose its methods as REST operations.
  10. // The WebService is added to the restful.DefaultContainer.
  11. // A ProductResource is typically created using some data access object.
  12. //
  13. // GET http://localhost:8080/products/1
  14. // POST http://localhost:8080/products
  15. // <Product><Id>1</Id><Title>The First</Title></Product>
  16. type Product struct {
  17. Id, Title string
  18. }
  19. type ProductResource struct {
  20. // typically reference a DAO (data-access-object)
  21. }
  22. func (p ProductResource) getOne(req *restful.Request, resp *restful.Response) {
  23. id := req.PathParameter("id")
  24. log.Println("getting product with id:" + id)
  25. resp.WriteEntity(Product{Id: id, Title: "test"})
  26. }
  27. func (p ProductResource) postOne(req *restful.Request, resp *restful.Response) {
  28. updatedProduct := new(Product)
  29. err := req.ReadEntity(updatedProduct)
  30. if err != nil { // bad request
  31. resp.WriteErrorString(http.StatusBadRequest, err.Error())
  32. return
  33. }
  34. log.Println("updating product with id:" + updatedProduct.Id)
  35. }
  36. func (p ProductResource) Register() {
  37. ws := new(restful.WebService)
  38. ws.Path("/products")
  39. ws.Consumes(restful.MIME_XML)
  40. ws.Produces(restful.MIME_XML)
  41. ws.Route(ws.GET("/{id}").To(p.getOne).
  42. Doc("get the product by its id").
  43. Param(ws.PathParameter("id", "identifier of the product").DataType("string")))
  44. ws.Route(ws.POST("").To(p.postOne).
  45. Doc("update or create a product").
  46. Param(ws.BodyParameter("Product", "a Product (XML)").DataType("main.Product")))
  47. restful.Add(ws)
  48. }
  49. func main() {
  50. ProductResource{}.Register()
  51. http.ListenAndServe(":8080", nil)
  52. }