ghttp_server_config.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package ghttp
  7. import (
  8. "context"
  9. "crypto/tls"
  10. "fmt"
  11. "github.com/gogf/gf/internal/intlog"
  12. "github.com/gogf/gf/os/gres"
  13. "github.com/gogf/gf/util/gutil"
  14. "net/http"
  15. "strconv"
  16. "time"
  17. "github.com/gogf/gf/util/gconv"
  18. "github.com/gogf/gf/os/gsession"
  19. "github.com/gogf/gf/os/gview"
  20. "github.com/gogf/gf/os/gfile"
  21. "github.com/gogf/gf/os/glog"
  22. )
  23. const (
  24. defaultHttpAddr = ":80" // Default listening port for HTTP.
  25. defaultHttpsAddr = ":443" // Default listening port for HTTPS.
  26. URI_TYPE_DEFAULT = 0 // Deprecated, please use UriTypeDefault instead.
  27. URI_TYPE_FULLNAME = 1 // Deprecated, please use UriTypeFullName instead.
  28. URI_TYPE_ALLLOWER = 2 // Deprecated, please use UriTypeAllLower instead.
  29. URI_TYPE_CAMEL = 3 // Deprecated, please use UriTypeCamel instead.
  30. UriTypeDefault = 0 // Method name to URI converting type, which converts name to its lower case and joins the words using char '-'.
  31. UriTypeFullName = 1 // Method name to URI converting type, which does no converting to the method name.
  32. UriTypeAllLower = 2 // Method name to URI converting type, which converts name to its lower case.
  33. UriTypeCamel = 3 // Method name to URI converting type, which converts name to its camel case.
  34. )
  35. // ServerConfig is the HTTP Server configuration manager.
  36. type ServerConfig struct {
  37. // ==================================
  38. // Basic.
  39. // ==================================
  40. // Address specifies the server listening address like "port" or ":port",
  41. // multiple addresses joined using ','.
  42. Address string `json:"address"`
  43. // HTTPSAddr specifies the HTTPS addresses, multiple addresses joined using char ','.
  44. HTTPSAddr string `json:"httpsAddr"`
  45. // HTTPSCertPath specifies certification file path for HTTPS service.
  46. HTTPSCertPath string `json:"httpsCertPath"`
  47. // HTTPSKeyPath specifies the key file path for HTTPS service.
  48. HTTPSKeyPath string `json:"httpsKeyPath"`
  49. // TLSConfig optionally provides a TLS configuration for use
  50. // by ServeTLS and ListenAndServeTLS. Note that this value is
  51. // cloned by ServeTLS and ListenAndServeTLS, so it's not
  52. // possible to modify the configuration with methods like
  53. // tls.Config.SetSessionTicketKeys. To use
  54. // SetSessionTicketKeys, use Server.Serve with a TLS Listener
  55. // instead.
  56. TLSConfig *tls.Config `json:"tlsConfig"`
  57. // Handler the handler for HTTP request.
  58. Handler http.Handler `json:"-"`
  59. // ReadTimeout is the maximum duration for reading the entire
  60. // request, including the body.
  61. //
  62. // Because ReadTimeout does not let Handlers make per-request
  63. // decisions on each request body's acceptable deadline or
  64. // upload rate, most users will prefer to use
  65. // ReadHeaderTimeout. It is valid to use them both.
  66. ReadTimeout time.Duration `json:"readTimeout"`
  67. // WriteTimeout is the maximum duration before timing out
  68. // writes of the response. It is reset whenever a new
  69. // request's header is read. Like ReadTimeout, it does not
  70. // let Handlers make decisions on a per-request basis.
  71. WriteTimeout time.Duration `json:"writeTimeout"`
  72. // IdleTimeout is the maximum amount of time to wait for the
  73. // next request when keep-alives are enabled. If IdleTimeout
  74. // is zero, the value of ReadTimeout is used. If both are
  75. // zero, there is no timeout.
  76. IdleTimeout time.Duration `json:"idleTimeout"`
  77. // MaxHeaderBytes controls the maximum number of bytes the
  78. // server will read parsing the request header's keys and
  79. // values, including the request line. It does not limit the
  80. // size of the request body.
  81. //
  82. // It can be configured in configuration file using string like: 1m, 10m, 500kb etc.
  83. // It's 10240 bytes in default.
  84. MaxHeaderBytes int `json:"maxHeaderBytes"`
  85. // KeepAlive enables HTTP keep-alive.
  86. KeepAlive bool `json:"keepAlive"`
  87. // ServerAgent specifies the server agent information, which is wrote to
  88. // HTTP response header as "Server".
  89. ServerAgent string `json:"serverAgent"`
  90. // View specifies the default template view object for the server.
  91. View *gview.View `json:"view"`
  92. // ==================================
  93. // Static.
  94. // ==================================
  95. // Rewrites specifies the URI rewrite rules map.
  96. Rewrites map[string]string `json:"rewrites"`
  97. // IndexFiles specifies the index files for static folder.
  98. IndexFiles []string `json:"indexFiles"`
  99. // IndexFolder specifies if listing sub-files when requesting folder.
  100. // The server responses HTTP status code 403 if it is false.
  101. IndexFolder bool `json:"indexFolder"`
  102. // ServerRoot specifies the root directory for static service.
  103. ServerRoot string `json:"serverRoot"`
  104. // SearchPaths specifies additional searching directories for static service.
  105. SearchPaths []string `json:"searchPaths"`
  106. // StaticPaths specifies URI to directory mapping array.
  107. StaticPaths []staticPathItem `json:"staticPaths"`
  108. // FileServerEnabled is the global switch for static service.
  109. // It is automatically set enabled if any static path is set.
  110. FileServerEnabled bool `json:"fileServerEnabled"`
  111. // ==================================
  112. // Cookie.
  113. // ==================================
  114. // CookieMaxAge specifies the max TTL for cookie items.
  115. CookieMaxAge time.Duration `json:"cookieMaxAge"`
  116. // CookiePath specifies cookie path.
  117. // It also affects the default storage for session id.
  118. CookiePath string `json:"cookiePath"`
  119. // CookieDomain specifies cookie domain.
  120. // It also affects the default storage for session id.
  121. CookieDomain string `json:"cookieDomain"`
  122. // ==================================
  123. // Session.
  124. // ==================================
  125. // SessionIdName specifies the session id name.
  126. SessionIdName string `json:"sessionIdName"`
  127. // SessionMaxAge specifies max TTL for session items.
  128. SessionMaxAge time.Duration `json:"sessionMaxAge"`
  129. // SessionPath specifies the session storage directory path for storing session files.
  130. // It only makes sense if the session storage is type of file storage.
  131. SessionPath string `json:"sessionPath"`
  132. // SessionStorage specifies the session storage.
  133. SessionStorage gsession.Storage `json:"sessionStorage"`
  134. // SessionCookieMaxAge specifies the cookie ttl for session id.
  135. // It it is set 0, it means it expires along with browser session.
  136. SessionCookieMaxAge time.Duration `json:"sessionCookieMaxAge"`
  137. // SessionCookieOutput specifies whether automatic outputting session id to cookie.
  138. SessionCookieOutput bool `json:"sessionCookieOutput"`
  139. // ==================================
  140. // Logging.
  141. // ==================================
  142. Logger *glog.Logger `json:"logger"` // Logger specifies the logger for server.
  143. LogPath string `json:"logPath"` // LogPath specifies the directory for storing logging files.
  144. LogLevel string `json:"logLevel"` // LogLevel specifies the logging level for logger.
  145. LogStdout bool `json:"logStdout"` // LogStdout specifies whether printing logging content to stdout.
  146. ErrorStack bool `json:"errorStack"` // ErrorStack specifies whether logging stack information when error.
  147. ErrorLogEnabled bool `json:"errorLogEnabled"` // ErrorLogEnabled enables error logging content to files.
  148. ErrorLogPattern string `json:"errorLogPattern"` // ErrorLogPattern specifies the error log file pattern like: error-{Ymd}.log
  149. AccessLogEnabled bool `json:"accessLogEnabled"` // AccessLogEnabled enables access logging content to files.
  150. AccessLogPattern string `json:"accessLogPattern"` // AccessLogPattern specifies the error log file pattern like: access-{Ymd}.log
  151. // ==================================
  152. // PProf.
  153. // ==================================
  154. PProfEnabled bool `json:"pprofEnabled"` // PProfEnabled enables PProf feature.
  155. PProfPattern string `json:"pprofPattern"` // PProfPattern specifies the PProf service pattern for router.
  156. // ==================================
  157. // Other.
  158. // ==================================
  159. // ClientMaxBodySize specifies the max body size limit in bytes for client request.
  160. // It can be configured in configuration file using string like: 1m, 10m, 500kb etc.
  161. // It's 8MB in default.
  162. ClientMaxBodySize int64 `json:"clientMaxBodySize"`
  163. // FormParsingMemory specifies max memory buffer size in bytes which can be used for
  164. // parsing multimedia form.
  165. // It can be configured in configuration file using string like: 1m, 10m, 500kb etc.
  166. // It's 1MB in default.
  167. FormParsingMemory int64 `json:"formParsingMemory"`
  168. // NameToUriType specifies the type for converting struct method name to URI when
  169. // registering routes.
  170. NameToUriType int `json:"nameToUriType"`
  171. // RouteOverWrite allows overwrite the route if duplicated.
  172. RouteOverWrite bool `json:"routeOverWrite"`
  173. // DumpRouterMap specifies whether automatically dumps router map when server starts.
  174. DumpRouterMap bool `json:"dumpRouterMap"`
  175. // Graceful enables graceful reload feature for all servers of the process.
  176. Graceful bool `json:"graceful"`
  177. // GracefulTimeout set the maximum survival time (seconds) of the parent process.
  178. GracefulTimeout uint8 `json:"gracefulTimeout"`
  179. }
  180. // Config creates and returns a ServerConfig object with default configurations.
  181. // Deprecated. Use NewConfig instead.
  182. func Config() ServerConfig {
  183. return NewConfig()
  184. }
  185. // NewConfig creates and returns a ServerConfig object with default configurations.
  186. // Note that, do not define this default configuration to local package variable, as there are
  187. // some pointer attributes that may be shared in different servers.
  188. func NewConfig() ServerConfig {
  189. return ServerConfig{
  190. Address: "",
  191. HTTPSAddr: "",
  192. Handler: nil,
  193. ReadTimeout: 60 * time.Second,
  194. WriteTimeout: 0, // No timeout.
  195. IdleTimeout: 60 * time.Second,
  196. MaxHeaderBytes: 10240, // 10KB
  197. KeepAlive: true,
  198. IndexFiles: []string{"index.html", "index.htm"},
  199. IndexFolder: false,
  200. ServerAgent: "GF HTTP Server",
  201. ServerRoot: "",
  202. StaticPaths: make([]staticPathItem, 0),
  203. FileServerEnabled: false,
  204. CookieMaxAge: time.Hour * 24 * 365,
  205. CookiePath: "/",
  206. CookieDomain: "",
  207. SessionIdName: "gfsessionid",
  208. SessionPath: gsession.DefaultStorageFilePath,
  209. SessionMaxAge: time.Hour * 24,
  210. SessionCookieOutput: true,
  211. SessionCookieMaxAge: time.Hour * 24,
  212. Logger: glog.New(),
  213. LogLevel: "all",
  214. LogStdout: true,
  215. ErrorStack: true,
  216. ErrorLogEnabled: true,
  217. ErrorLogPattern: "error-{Ymd}.log",
  218. AccessLogEnabled: false,
  219. AccessLogPattern: "access-{Ymd}.log",
  220. DumpRouterMap: true,
  221. ClientMaxBodySize: 8 * 1024 * 1024, // 8MB
  222. FormParsingMemory: 1024 * 1024, // 1MB
  223. Rewrites: make(map[string]string),
  224. Graceful: false,
  225. GracefulTimeout: 2, // seconds
  226. }
  227. }
  228. // ConfigFromMap creates and returns a ServerConfig object with given map and
  229. // default configuration object.
  230. func ConfigFromMap(m map[string]interface{}) (ServerConfig, error) {
  231. config := NewConfig()
  232. if err := gconv.Struct(m, &config); err != nil {
  233. return config, err
  234. }
  235. return config, nil
  236. }
  237. // SetConfigWithMap sets the configuration for the server using map.
  238. func (s *Server) SetConfigWithMap(m map[string]interface{}) error {
  239. // The m now is a shallow copy of m.
  240. // Any changes to m does not affect the original one.
  241. // A little tricky, isn't it?
  242. m = gutil.MapCopy(m)
  243. // Allow setting the size configuration items using string size like:
  244. // 1m, 100mb, 512kb, etc.
  245. if k, v := gutil.MapPossibleItemByKey(m, "MaxHeaderBytes"); k != "" {
  246. m[k] = gfile.StrToSize(gconv.String(v))
  247. }
  248. if k, v := gutil.MapPossibleItemByKey(m, "ClientMaxBodySize"); k != "" {
  249. m[k] = gfile.StrToSize(gconv.String(v))
  250. }
  251. if k, v := gutil.MapPossibleItemByKey(m, "FormParsingMemory"); k != "" {
  252. m[k] = gfile.StrToSize(gconv.String(v))
  253. }
  254. // Update the current configuration object.
  255. // It only updates the configured keys not all the object.
  256. if err := gconv.Struct(m, &s.config); err != nil {
  257. return err
  258. }
  259. return s.SetConfig(s.config)
  260. }
  261. // SetConfig sets the configuration for the server.
  262. func (s *Server) SetConfig(c ServerConfig) error {
  263. s.config = c
  264. // Static.
  265. if c.ServerRoot != "" {
  266. s.SetServerRoot(c.ServerRoot)
  267. }
  268. if len(c.SearchPaths) > 0 {
  269. paths := c.SearchPaths
  270. c.SearchPaths = []string{}
  271. for _, v := range paths {
  272. s.AddSearchPath(v)
  273. }
  274. }
  275. // HTTPS.
  276. if c.TLSConfig == nil && c.HTTPSCertPath != "" {
  277. s.EnableHTTPS(c.HTTPSCertPath, c.HTTPSKeyPath)
  278. }
  279. // Logging.
  280. if s.config.LogPath != "" && s.config.LogPath != s.config.Logger.GetPath() {
  281. if err := s.config.Logger.SetPath(s.config.LogPath); err != nil {
  282. return err
  283. }
  284. }
  285. if err := s.config.Logger.SetLevelStr(s.config.LogLevel); err != nil {
  286. intlog.Error(context.TODO(), err)
  287. }
  288. SetGraceful(c.Graceful)
  289. intlog.Printf(context.TODO(), "SetConfig: %+v", s.config)
  290. return nil
  291. }
  292. // SetAddr sets the listening address for the server.
  293. // The address is like ':80', '0.0.0.0:80', '127.0.0.1:80', '180.18.99.10:80', etc.
  294. func (s *Server) SetAddr(address string) {
  295. s.config.Address = address
  296. }
  297. // SetPort sets the listening ports for the server.
  298. // The listening ports can be multiple like: SetPort(80, 8080).
  299. func (s *Server) SetPort(port ...int) {
  300. if len(port) > 0 {
  301. s.config.Address = ""
  302. for _, v := range port {
  303. if len(s.config.Address) > 0 {
  304. s.config.Address += ","
  305. }
  306. s.config.Address += ":" + strconv.Itoa(v)
  307. }
  308. }
  309. }
  310. // SetHTTPSAddr sets the HTTPS listening ports for the server.
  311. func (s *Server) SetHTTPSAddr(address string) {
  312. s.config.HTTPSAddr = address
  313. }
  314. // SetHTTPSPort sets the HTTPS listening ports for the server.
  315. // The listening ports can be multiple like: SetHTTPSPort(443, 500).
  316. func (s *Server) SetHTTPSPort(port ...int) {
  317. if len(port) > 0 {
  318. s.config.HTTPSAddr = ""
  319. for _, v := range port {
  320. if len(s.config.HTTPSAddr) > 0 {
  321. s.config.HTTPSAddr += ","
  322. }
  323. s.config.HTTPSAddr += ":" + strconv.Itoa(v)
  324. }
  325. }
  326. }
  327. // EnableHTTPS enables HTTPS with given certification and key files for the server.
  328. // The optional parameter <tlsConfig> specifies custom TLS configuration.
  329. func (s *Server) EnableHTTPS(certFile, keyFile string, tlsConfig ...*tls.Config) {
  330. certFileRealPath := gfile.RealPath(certFile)
  331. if certFileRealPath == "" {
  332. certFileRealPath = gfile.RealPath(gfile.Pwd() + gfile.Separator + certFile)
  333. if certFileRealPath == "" {
  334. certFileRealPath = gfile.RealPath(gfile.MainPkgPath() + gfile.Separator + certFile)
  335. }
  336. }
  337. // Resource.
  338. if certFileRealPath == "" && gres.Contains(certFile) {
  339. certFileRealPath = certFile
  340. }
  341. if certFileRealPath == "" {
  342. s.Logger().Fatal(fmt.Sprintf(`EnableHTTPS failed: certFile "%s" does not exist`, certFile))
  343. }
  344. keyFileRealPath := gfile.RealPath(keyFile)
  345. if keyFileRealPath == "" {
  346. keyFileRealPath = gfile.RealPath(gfile.Pwd() + gfile.Separator + keyFile)
  347. if keyFileRealPath == "" {
  348. keyFileRealPath = gfile.RealPath(gfile.MainPkgPath() + gfile.Separator + keyFile)
  349. }
  350. }
  351. // Resource.
  352. if keyFileRealPath == "" && gres.Contains(keyFile) {
  353. keyFileRealPath = keyFile
  354. }
  355. if keyFileRealPath == "" {
  356. s.Logger().Fatal(fmt.Sprintf(`EnableHTTPS failed: keyFile "%s" does not exist`, keyFile))
  357. }
  358. s.config.HTTPSCertPath = certFileRealPath
  359. s.config.HTTPSKeyPath = keyFileRealPath
  360. if len(tlsConfig) > 0 {
  361. s.config.TLSConfig = tlsConfig[0]
  362. }
  363. }
  364. // SetTLSConfig sets custom TLS configuration and enables HTTPS feature for the server.
  365. func (s *Server) SetTLSConfig(tlsConfig *tls.Config) {
  366. s.config.TLSConfig = tlsConfig
  367. }
  368. // SetReadTimeout sets the ReadTimeout for the server.
  369. func (s *Server) SetReadTimeout(t time.Duration) {
  370. s.config.ReadTimeout = t
  371. }
  372. // SetWriteTimeout sets the WriteTimeout for the server.
  373. func (s *Server) SetWriteTimeout(t time.Duration) {
  374. s.config.WriteTimeout = t
  375. }
  376. // SetIdleTimeout sets the IdleTimeout for the server.
  377. func (s *Server) SetIdleTimeout(t time.Duration) {
  378. s.config.IdleTimeout = t
  379. }
  380. // SetMaxHeaderBytes sets the MaxHeaderBytes for the server.
  381. func (s *Server) SetMaxHeaderBytes(b int) {
  382. s.config.MaxHeaderBytes = b
  383. }
  384. // SetServerAgent sets the ServerAgent for the server.
  385. func (s *Server) SetServerAgent(agent string) {
  386. s.config.ServerAgent = agent
  387. }
  388. // SetKeepAlive sets the KeepAlive for the server.
  389. func (s *Server) SetKeepAlive(enabled bool) {
  390. s.config.KeepAlive = enabled
  391. }
  392. // SetView sets the View for the server.
  393. func (s *Server) SetView(view *gview.View) {
  394. s.config.View = view
  395. }
  396. // GetName returns the name of the server.
  397. func (s *Server) GetName() string {
  398. return s.name
  399. }
  400. // Handler returns the request handler of the server.
  401. func (s *Server) Handler() http.Handler {
  402. if s.config.Handler == nil {
  403. return s
  404. }
  405. return s.config.Handler
  406. }