restful-swagger.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. "github.com/emicklei/go-restful"
  6. "github.com/emicklei/go-restful/swagger"
  7. )
  8. type Book struct {
  9. Title string
  10. Author string
  11. }
  12. func main() {
  13. ws := new(restful.WebService)
  14. ws.Path("/books")
  15. ws.Consumes(restful.MIME_JSON, restful.MIME_XML)
  16. ws.Produces(restful.MIME_JSON, restful.MIME_XML)
  17. restful.Add(ws)
  18. ws.Route(ws.GET("/{medium}").To(noop).
  19. Doc("Search all books").
  20. Param(ws.PathParameter("medium", "digital or paperback").DataType("string")).
  21. Param(ws.QueryParameter("language", "en,nl,de").DataType("string")).
  22. Param(ws.HeaderParameter("If-Modified-Since", "last known timestamp").DataType("datetime")).
  23. Do(returns200, returns500))
  24. ws.Route(ws.PUT("/{medium}").To(noop).
  25. Doc("Add a new book").
  26. Param(ws.PathParameter("medium", "digital or paperback").DataType("string")).
  27. Reads(Book{}))
  28. // You can install the Swagger Service which provides a nice Web UI on your REST API
  29. // You need to download the Swagger HTML5 assets and change the FilePath location in the config below.
  30. // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field.
  31. config := swagger.Config{
  32. WebServices: restful.DefaultContainer.RegisteredWebServices(), // you control what services are visible
  33. WebServicesUrl: "http://localhost:8080",
  34. ApiPath: "/apidocs.json",
  35. // Optionally, specifiy where the UI is located
  36. SwaggerPath: "/apidocs/",
  37. SwaggerFilePath: "/Users/emicklei/xProjects/swagger-ui/dist"}
  38. swagger.RegisterSwaggerService(config, restful.DefaultContainer)
  39. log.Printf("start listening on localhost:8080")
  40. server := &http.Server{Addr: ":8080", Handler: restful.DefaultContainer}
  41. log.Fatal(server.ListenAndServe())
  42. }
  43. func noop(req *restful.Request, resp *restful.Response) {}
  44. func returns200(b *restful.RouteBuilder) {
  45. b.Returns(http.StatusOK, "OK", Book{})
  46. }
  47. func returns500(b *restful.RouteBuilder) {
  48. b.Returns(http.StatusInternalServerError, "Bummer, something went wrong", nil)
  49. }