server.go 4.9 KB

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