server.go 4.5 KB

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