router.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package http
  2. import (
  3. "net/http"
  4. "runtime"
  5. "git.chuangxin1.com/csacred/toolkit"
  6. "github.com/chuangxin1/httprouter"
  7. )
  8. // Handle is a function that can be registered to a route to handle HTTP
  9. // requests. Like http.HandlerFunc.
  10. type Handle func(http.ResponseWriter, *http.Request)
  11. // NewRouter new http router with default route
  12. func NewRouter() *httprouter.Router {
  13. router := httprouter.New()
  14. router.NotFound = http.HandlerFunc(notFoundHandler)
  15. router.PanicHandler = panicHandler
  16. router.GET("/", defaultHandler)
  17. router.GET("/health", defaultHandler)
  18. //router.Handler("GET", "/metrics", promhttp.Handler())
  19. return router
  20. }
  21. func defaultHandler(w http.ResponseWriter, r *http.Request) {
  22. ver := map[string]string{
  23. "version": "0.2.0",
  24. "comments": "chuangxin1.com API"}
  25. WriteJSON(w, toolkit.RowReplyData(ver))
  26. }
  27. func panicHandler(w http.ResponseWriter, r *http.Request, err interface{}) {
  28. e := err.(runtime.Error)
  29. WriteJSON(w, toolkit.ErrReplyData(toolkit.ErrException, e.Error()))
  30. }
  31. func notFoundHandler(w http.ResponseWriter, req *http.Request) {
  32. WriteJSON(w, toolkit.ErrReplyData(toolkit.ErrNotFound, `NotFound`))
  33. }
  34. // AddHandler add handler to router
  35. func AddHandler(router *httprouter.Router, method, route string, handler http.Handler) {
  36. router.Handler(method, route, handler)
  37. }
  38. // AddGetHandle add handle to router
  39. func AddGetHandle(router *httprouter.Router, route string, handle Handle) {
  40. router.GET(route, httprouter.Handle(handle))
  41. }
  42. // AddPostHandle add handle to router
  43. func AddPostHandle(router *httprouter.Router, route string, handle Handle) {
  44. router.POST(route, httprouter.Handle(handle))
  45. }
  46. // AddPutHandle add handle to router
  47. func AddPutHandle(router *httprouter.Router, route string, handle Handle) {
  48. router.PUT(route, httprouter.Handle(handle))
  49. }
  50. // AddHeadHandle add handle to router
  51. func AddHeadHandle(router *httprouter.Router, route string, handle Handle) {
  52. router.HEAD(route, httprouter.Handle(handle))
  53. }
  54. // AddDeleteHandle add handle to router
  55. func AddDeleteHandle(router *httprouter.Router, route string, handle Handle) {
  56. router.DELETE(route, httprouter.Handle(handle))
  57. }
  58. // AddPatchHandle add handle to router
  59. func AddPatchHandle(router *httprouter.Router, route string, handle Handle) {
  60. router.PATCH(route, httprouter.Handle(handle))
  61. }
  62. // AddOptionsHandle add handle to router
  63. func AddOptionsHandle(router *httprouter.Router, route string, handle Handle) {
  64. router.OPTIONS(route, httprouter.Handle(handle))
  65. }