server.go 5.6 KB

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