server.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. package http
  2. import (
  3. "context"
  4. "embed"
  5. "git.nspix.com/golang/kos/entry/http/router"
  6. "net"
  7. "net/http"
  8. "path"
  9. "strings"
  10. "sync"
  11. "time"
  12. )
  13. var (
  14. ctxPool sync.Pool
  15. )
  16. type Server struct {
  17. ctx context.Context
  18. serve *http.Server
  19. router *router.Router
  20. middleware []Middleware
  21. uptime time.Time
  22. anyRequests map[string]http.Handler
  23. }
  24. func (svr *Server) applyContext() *Context {
  25. if v := ctxPool.Get(); v != nil {
  26. if ctx, ok := v.(*Context); ok {
  27. return ctx
  28. }
  29. }
  30. return &Context{}
  31. }
  32. func (svr *Server) releaseContext(ctx *Context) {
  33. ctxPool.Put(ctx)
  34. }
  35. func (svr *Server) wrapHandle(cb HandleFunc, middleware ...Middleware) router.Handle {
  36. return func(writer http.ResponseWriter, request *http.Request, params router.Params) {
  37. ctx := svr.applyContext()
  38. defer func() {
  39. svr.releaseContext(ctx)
  40. }()
  41. ps := make(map[string]string)
  42. for _, v := range params {
  43. ps[v.Key] = v.Value
  44. }
  45. ctx.reset(request, writer, ps)
  46. for i := len(svr.middleware) - 1; i >= 0; i-- {
  47. cb = svr.middleware[i](cb)
  48. }
  49. for i := len(middleware) - 1; i >= 0; i-- {
  50. cb = middleware[i](cb)
  51. }
  52. if err := cb(ctx); err != nil {
  53. ctx.Status(http.StatusServiceUnavailable)
  54. }
  55. }
  56. }
  57. func (svr *Server) Use(middleware ...Middleware) {
  58. svr.middleware = append(svr.middleware, middleware...)
  59. }
  60. func (svr *Server) Any(prefix string, handle http.Handler) {
  61. if !strings.HasPrefix(prefix, "/") {
  62. prefix = "/" + prefix
  63. }
  64. svr.anyRequests[prefix] = handle
  65. }
  66. func (svr *Server) Handle(method string, path string, cb HandleFunc, middleware ...Middleware) {
  67. if method == "" {
  68. method = http.MethodPost
  69. }
  70. if path == "" {
  71. path = "/"
  72. }
  73. if !strings.HasPrefix(path, "/") {
  74. path = "/" + path
  75. }
  76. svr.router.Replace(method, path, svr.wrapHandle(cb, middleware...))
  77. }
  78. func (svr *Server) Group(prefix string, routes []Route, middleware ...Middleware) {
  79. for _, route := range routes {
  80. svr.Handle(route.Method, path.Join(prefix, route.Path), route.Handle, middleware...)
  81. }
  82. }
  83. func (svr *Server) Embed(prefix string, root string, embedFs embed.FS) {
  84. routePath := prefix
  85. if !strings.HasSuffix(routePath, "/*filepath") {
  86. if strings.HasSuffix(routePath, "/") {
  87. routePath += "/"
  88. } else {
  89. routePath += "/*filepath"
  90. }
  91. }
  92. httpFs := http.FS(embedFs)
  93. svr.Handle(MethodGet, routePath, func(ctx *Context) (err error) {
  94. filename := strings.TrimPrefix(ctx.Request().URL.Path, prefix)
  95. if filename == "" || filename == "/" {
  96. filename = root + "/"
  97. if !strings.HasSuffix(filename, "/") {
  98. filename = filename + "/"
  99. }
  100. } else {
  101. if !strings.HasPrefix(filename, root) {
  102. filename = path.Clean(path.Join(root, filename))
  103. }
  104. }
  105. if !strings.HasPrefix(filename, "/") {
  106. filename = "/" + filename
  107. }
  108. ctx.Request().URL.Path = filename
  109. http.FileServer(newFS(svr.uptime, httpFs)).ServeHTTP(ctx.Response(), ctx.Request())
  110. return
  111. })
  112. }
  113. func (svr *Server) Static(path string, root http.FileSystem) {
  114. if !strings.HasSuffix(path, "/*filepath") {
  115. if strings.HasSuffix(path, "/") {
  116. path += "/"
  117. } else {
  118. path += "/*filepath"
  119. }
  120. }
  121. svr.router.ServeFiles(path, root)
  122. }
  123. func (svr *Server) handleOption(res http.ResponseWriter, req *http.Request) {
  124. res.Header().Add("Vary", "Origin")
  125. res.Header().Add("Vary", "Access-Control-Request-Method")
  126. res.Header().Add("Vary", "Access-Control-Request-Headers")
  127. res.Header().Set("Access-Control-Allow-Origin", "*")
  128. res.Header().Set("Access-Control-Allow-Credentials", "true")
  129. res.Header().Set("Access-Control-Allow-Methods", "GET,HEAD,PUT,PATCH,POST,DELETE")
  130. h := req.Header.Get("Access-Control-Request-Headers")
  131. if h != "" {
  132. res.Header().Set("Access-Control-Allow-Headers", h)
  133. }
  134. res.WriteHeader(http.StatusNoContent)
  135. }
  136. func (svr *Server) handleRequest(res http.ResponseWriter, req *http.Request) {
  137. res.Header().Add("Vary", "Origin")
  138. res.Header().Set("Access-Control-Allow-Origin", "*")
  139. res.Header().Set("Access-Control-Allow-Credentials", "true")
  140. h := req.Header.Get("Access-Control-Request-Headers")
  141. if h != "" {
  142. res.Header().Set("Access-Control-Allow-Headers", h)
  143. }
  144. svr.router.ServeHTTP(res, req)
  145. }
  146. func (svr *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
  147. for prefix, handle := range svr.anyRequests {
  148. if strings.HasPrefix(request.URL.Path, prefix) {
  149. handle.ServeHTTP(writer, request)
  150. return
  151. }
  152. }
  153. switch request.Method {
  154. case http.MethodOptions:
  155. svr.handleOption(writer, request)
  156. default:
  157. svr.handleRequest(writer, request)
  158. }
  159. }
  160. func (svr *Server) Serve(l net.Listener) (err error) {
  161. svr.serve = &http.Server{
  162. Handler: svr,
  163. }
  164. svr.router.NotFound = NotFound{}
  165. svr.router.MethodNotAllowed = NotAllowed{}
  166. return svr.serve.Serve(l)
  167. }
  168. func (svr *Server) Shutdown() (err error) {
  169. if svr.serve != nil {
  170. err = svr.serve.Shutdown(svr.ctx)
  171. }
  172. return
  173. }
  174. func New(ctx context.Context) *Server {
  175. svr := &Server{
  176. ctx: ctx,
  177. uptime: time.Now(),
  178. router: router.New(),
  179. anyRequests: make(map[string]http.Handler),
  180. middleware: make([]Middleware, 0, 10),
  181. }
  182. return svr
  183. }