app.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. // ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
  2. // 🤖 Github Repository: https://github.com/gofiber/fiber
  3. // 📌 API Documentation: https://docs.gofiber.io
  4. // Package fiber
  5. // Fiber is an Express inspired web framework built on top of Fasthttp,
  6. // the fastest HTTP engine for Go. Designed to ease things up for fast
  7. // development with zero memory allocation and performance in mind.
  8. package fiber
  9. import (
  10. "bufio"
  11. "crypto/tls"
  12. "fmt"
  13. "io"
  14. "net"
  15. "net/http"
  16. "net/http/httputil"
  17. "os"
  18. "reflect"
  19. "runtime"
  20. "strconv"
  21. "strings"
  22. "sync"
  23. "time"
  24. utils "github.com/gofiber/utils"
  25. colorable "github.com/mattn/go-colorable"
  26. isatty "github.com/mattn/go-isatty"
  27. fasthttp "github.com/valyala/fasthttp"
  28. )
  29. // Version of current package
  30. const Version = "1.14.6"
  31. // Map is a shortcut for map[string]interface{}, useful for JSON returns
  32. type Map map[string]interface{}
  33. // Handler defines a function to serve HTTP requests.
  34. type Handler = func(*Ctx)
  35. // Error represents an error that occurred while handling a request.
  36. type Error struct {
  37. Code int `json:"code"`
  38. Message string `json:"message"`
  39. }
  40. // App denotes the Fiber application.
  41. type App struct {
  42. out io.Writer
  43. mutex sync.Mutex
  44. // Route stack divided by HTTP methods
  45. stack [][]*Route
  46. // Route stack divided by HTTP methods and route prefixes
  47. treeStack []map[string][]*Route
  48. // Amount of registered routes
  49. routesCount int
  50. // Amount of registered handlers
  51. handlerCount int
  52. // Ctx pool
  53. pool sync.Pool
  54. // Fasthttp server
  55. server *fasthttp.Server
  56. // App settings
  57. Settings *Settings `json:"settings"`
  58. }
  59. // Settings is a struct holding the server settings.
  60. type Settings struct {
  61. // ErrorHandler is executed when you pass an error in the Next(err) method.
  62. // This function is also executed when middleware.Recover() catches a panic
  63. // Default: func(ctx *Ctx, err error) {
  64. // code := StatusInternalServerError
  65. // if e, ok := err.(*Error); ok {
  66. // code = e.Code
  67. // }
  68. // ctx.Set(HeaderContentType, MIMETextPlainCharsetUTF8)
  69. // ctx.Status(code).SendString(err.Error())
  70. // }
  71. ErrorHandler func(*Ctx, error) `json:"-"`
  72. // Enables the "Server: value" HTTP header.
  73. // Default: ""
  74. ServerHeader string `json:"server_header"`
  75. // When set to true, the router treats "/foo" and "/foo/" as different.
  76. // By default this is disabled and both "/foo" and "/foo/" will execute the same handler.
  77. StrictRouting bool `json:"strict_routing"`
  78. // When set to true, enables case sensitive routing.
  79. // E.g. "/FoO" and "/foo" are treated as different routes.
  80. // By default this is disabled and both "/FoO" and "/foo" will execute the same handler.
  81. CaseSensitive bool `json:"case_sensitive"`
  82. // When set to true, this relinquishes the 0-allocation promise in certain
  83. // cases in order to access the handler values (e.g. request bodies) in an
  84. // immutable fashion so that these values are available even if you return
  85. // from handler.
  86. // Default: false
  87. Immutable bool `json:"immutable"`
  88. // When set to true, converts all encoded characters in the route back
  89. // before setting the path for the context, so that the routing can also
  90. // work with urlencoded special characters.
  91. // Default: false
  92. UnescapePath bool `json:"unescape_path"`
  93. // Enable or disable ETag header generation, since both weak and strong etags are generated
  94. // using the same hashing method (CRC-32). Weak ETags are the default when enabled.
  95. // Default: false
  96. ETag bool `json:"etag"`
  97. // When set to true, this will spawn multiple Go processes listening on the same port.
  98. // Default: false
  99. Prefork bool `json:"prefork"`
  100. // Max body size that the server accepts.
  101. // Default: 4 * 1024 * 1024
  102. BodyLimit int `json:"body_limit"`
  103. // Maximum number of concurrent connections.
  104. // Default: 256 * 1024
  105. Concurrency int `json:"concurrency"`
  106. // When set to true, disables keep-alive connections.
  107. // The server will close incoming connections after sending the first response to client.
  108. // Default: false
  109. DisableKeepalive bool `json:"disable_keep_alive"`
  110. // When set to true, causes the default date header to be excluded from the response.
  111. // Default: false
  112. DisableDefaultDate bool `json:"disable_default_date"`
  113. // When set to true, causes the default Content-Type header to be excluded from the response.
  114. // Default: false
  115. DisableDefaultContentType bool `json:"disable_default_content_type"`
  116. // When set to true, disables header normalization.
  117. // By default all header names are normalized: conteNT-tYPE -> Content-Type.
  118. // Default: false
  119. DisableHeaderNormalizing bool `json:"disable_header_normalizing"`
  120. // When set to true, it will not print out the «Fiber» ASCII art and listening address.
  121. // Default: false
  122. DisableStartupMessage bool `json:"disable_startup_message"`
  123. // Views is the interface that wraps the Render function.
  124. // Default: nil
  125. Views Views `json:"-"`
  126. // The amount of time allowed to read the full request including body.
  127. // It is reset after the request handler has returned.
  128. // The connection's read deadline is reset when the connection opens.
  129. // Default: unlimited
  130. ReadTimeout time.Duration `json:"read_timeout"`
  131. // The maximum duration before timing out writes of the response.
  132. // It is reset after the request handler has returned.
  133. // Default: unlimited
  134. WriteTimeout time.Duration `json:"write_timeout"`
  135. // The maximum amount of time to wait for the next request when keep-alive is enabled.
  136. // If IdleTimeout is zero, the value of ReadTimeout is used.
  137. // Default: unlimited
  138. IdleTimeout time.Duration `json:"idle_timeout"`
  139. // Per-connection buffer size for requests' reading.
  140. // This also limits the maximum header size.
  141. // Increase this buffer if your clients send multi-KB RequestURIs
  142. // and/or multi-KB headers (for example, BIG cookies).
  143. // Default: 4096
  144. ReadBufferSize int `json:"read_buffer_size"`
  145. // Per-connection buffer size for responses' writing.
  146. // Default: 4096
  147. WriteBufferSize int `json:"write_buffer_size"`
  148. // CompressedFileSuffix adds suffix to the original file name and
  149. // tries saving the resulting compressed file under the new file name.
  150. // Default: ".fiber.gz"
  151. CompressedFileSuffix string `json:"compressed_file_suffix"`
  152. // FEATURE: v1.13
  153. // The router executes the same handler by default if StrictRouting or CaseSensitive is disabled.
  154. // Enabling RedirectFixedPath will change this behaviour into a client redirect to the original route path.
  155. // Using the status code 301 for GET requests and 308 for all other request methods.
  156. // RedirectFixedPath bool
  157. }
  158. // Static defines configuration options when defining static assets.
  159. type Static struct {
  160. // When set to true, the server tries minimizing CPU usage by caching compressed files.
  161. // This works differently than the github.com/gofiber/compression middleware.
  162. // Optional. Default value false
  163. Compress bool
  164. // When set to true, enables byte range requests.
  165. // Optional. Default value false
  166. ByteRange bool
  167. // When set to true, enables directory browsing.
  168. // Optional. Default value false.
  169. Browse bool
  170. // The name of the index file for serving a directory.
  171. // Optional. Default value "index.html".
  172. Index string
  173. }
  174. // default settings
  175. const (
  176. defaultBodyLimit = 4 * 1024 * 1024
  177. defaultConcurrency = 256 * 1024
  178. defaultReadBufferSize = 4096
  179. defaultWriteBufferSize = 4096
  180. defaultCompressedFileSuffix = ".fiber.gz"
  181. )
  182. var defaultErrorHandler = func(ctx *Ctx, err error) {
  183. code := StatusInternalServerError
  184. if e, ok := err.(*Error); ok {
  185. code = e.Code
  186. }
  187. ctx.Set(HeaderContentType, MIMETextPlainCharsetUTF8)
  188. ctx.Status(code).SendString(err.Error())
  189. }
  190. // New creates a new Fiber named instance.
  191. // myApp := app.New()
  192. // You can pass an optional settings by passing a *Settings struct:
  193. // myApp := app.New(&fiber.Settings{
  194. // Prefork: true,
  195. // ServerHeader: "Fiber",
  196. // })
  197. func New(settings ...*Settings) *App {
  198. // Create a new app
  199. app := &App{
  200. // Create router stack
  201. stack: make([][]*Route, len(intMethod)),
  202. treeStack: make([]map[string][]*Route, len(intMethod)),
  203. // Create Ctx pool
  204. pool: sync.Pool{
  205. New: func() interface{} {
  206. return new(Ctx)
  207. },
  208. },
  209. // Set settings
  210. Settings: &Settings{},
  211. }
  212. // Overwrite settings if provided
  213. if len(settings) > 0 {
  214. app.Settings = settings[0]
  215. }
  216. if app.Settings.BodyLimit <= 0 {
  217. app.Settings.BodyLimit = defaultBodyLimit
  218. }
  219. if app.Settings.Concurrency <= 0 {
  220. app.Settings.Concurrency = defaultConcurrency
  221. }
  222. if app.Settings.ReadBufferSize <= 0 {
  223. app.Settings.ReadBufferSize = defaultReadBufferSize
  224. }
  225. if app.Settings.WriteBufferSize <= 0 {
  226. app.Settings.WriteBufferSize = defaultWriteBufferSize
  227. }
  228. if app.Settings.CompressedFileSuffix == "" {
  229. app.Settings.CompressedFileSuffix = defaultCompressedFileSuffix
  230. }
  231. if app.Settings.ErrorHandler == nil {
  232. app.Settings.ErrorHandler = defaultErrorHandler
  233. }
  234. if app.Settings.Immutable {
  235. getBytes, getString = getBytesImmutable, getStringImmutable
  236. }
  237. // Return app
  238. return app
  239. }
  240. // Use registers a middleware route.
  241. // Middleware matches requests beginning with the provided prefix.
  242. // Providing a prefix is optional, it defaults to "/".
  243. //
  244. // app.Use(handler)
  245. // app.Use("/api", handler)
  246. // app.Use("/api", handler, handler)
  247. func (app *App) Use(args ...interface{}) Router {
  248. var prefix string
  249. var handlers []Handler
  250. for i := 0; i < len(args); i++ {
  251. switch arg := args[i].(type) {
  252. case string:
  253. prefix = arg
  254. case Handler:
  255. handlers = append(handlers, arg)
  256. default:
  257. panic(fmt.Sprintf("use: invalid handler %v\n", reflect.TypeOf(arg)))
  258. }
  259. }
  260. app.register(methodUse, prefix, handlers...)
  261. return app
  262. }
  263. // Get registers a route for GET methods that requests a representation
  264. // of the specified resource. Requests using GET should only retrieve data.
  265. func (app *App) Get(path string, handlers ...Handler) Router {
  266. route := app.register(MethodGet, path, handlers...)
  267. // Add HEAD route
  268. headRoute := route
  269. app.addRoute(MethodHead, &headRoute)
  270. return app
  271. }
  272. // Head registers a route for HEAD methods that asks for a response identical
  273. // to that of a GET request, but without the response body.
  274. func (app *App) Head(path string, handlers ...Handler) Router {
  275. return app.Add(MethodHead, path, handlers...)
  276. }
  277. // Post registers a route for POST methods that is used to submit an entity to the
  278. // specified resource, often causing a change in state or side effects on the server.
  279. func (app *App) Post(path string, handlers ...Handler) Router {
  280. return app.Add(MethodPost, path, handlers...)
  281. }
  282. // Put registers a route for PUT methods that replaces all current representations
  283. // of the target resource with the request payload.
  284. func (app *App) Put(path string, handlers ...Handler) Router {
  285. return app.Add(MethodPut, path, handlers...)
  286. }
  287. // Delete registers a route for DELETE methods that deletes the specified resource.
  288. func (app *App) Delete(path string, handlers ...Handler) Router {
  289. return app.Add(MethodDelete, path, handlers...)
  290. }
  291. // Connect registers a route for CONNECT methods that establishes a tunnel to the
  292. // server identified by the target resource.
  293. func (app *App) Connect(path string, handlers ...Handler) Router {
  294. return app.Add(MethodConnect, path, handlers...)
  295. }
  296. // Options registers a route for OPTIONS methods that is used to describe the
  297. // communication options for the target resource.
  298. func (app *App) Options(path string, handlers ...Handler) Router {
  299. return app.Add(MethodOptions, path, handlers...)
  300. }
  301. // Trace registers a route for TRACE methods that performs a message loop-back
  302. // test along the path to the target resource.
  303. func (app *App) Trace(path string, handlers ...Handler) Router {
  304. return app.Add(MethodTrace, path, handlers...)
  305. }
  306. // Patch registers a route for PATCH methods that is used to apply partial
  307. // modifications to a resource.
  308. func (app *App) Patch(path string, handlers ...Handler) Router {
  309. return app.Add(MethodPatch, path, handlers...)
  310. }
  311. // Add ...
  312. func (app *App) Add(method, path string, handlers ...Handler) Router {
  313. app.register(method, path, handlers...)
  314. return app
  315. }
  316. // Static ...
  317. func (app *App) Static(prefix, root string, config ...Static) Router {
  318. app.registerStatic(prefix, root, config...)
  319. return app
  320. }
  321. // All ...
  322. func (app *App) All(path string, handlers ...Handler) Router {
  323. for _, method := range intMethod {
  324. app.Add(method, path, handlers...)
  325. }
  326. return app
  327. }
  328. // Group is used for Routes with common prefix to define a new sub-router with optional middleware.
  329. func (app *App) Group(prefix string, handlers ...Handler) Router {
  330. if len(handlers) > 0 {
  331. app.register(methodUse, prefix, handlers...)
  332. }
  333. return &Group{prefix: prefix, app: app}
  334. }
  335. // Error makes it compatible with `error` interface.
  336. func (e *Error) Error() string {
  337. return e.Message
  338. }
  339. // NewError creates a new HTTPError instance.
  340. func NewError(code int, message ...string) *Error {
  341. e := &Error{code, utils.StatusMessage(code)}
  342. if len(message) > 0 {
  343. e.Message = message[0]
  344. }
  345. return e
  346. }
  347. // Routes returns all registered routes
  348. // for _, r := range app.Routes() {
  349. // fmt.Printf("%s\t%s\n", r.Method, r.Path)
  350. // }
  351. func (app *App) Routes() []*Route {
  352. fmt.Println("routes is deprecated since v1.13.2, please use `app.Stack()` to access the raw router stack")
  353. routes := make([]*Route, 0)
  354. for m := range app.stack {
  355. stackLoop:
  356. for r := range app.stack[m] {
  357. // Don't duplicate USE routesCount
  358. if app.stack[m][r].use {
  359. for i := range routes {
  360. if routes[i].use && routes[i].Path == app.stack[m][r].Path {
  361. continue stackLoop
  362. }
  363. }
  364. }
  365. routes = append(routes, app.stack[m][r])
  366. }
  367. }
  368. return routes
  369. }
  370. // Listener can be used to pass a custom listener.
  371. // You can pass an optional *tls.Config to enable TLS.
  372. // This method does not support the Prefork feature
  373. // To use Prefork, please use app.Listen()
  374. func (app *App) Listener(ln net.Listener, tlsconfig ...*tls.Config) error {
  375. // Update server settings
  376. app.init()
  377. // TLS config
  378. if len(tlsconfig) > 0 {
  379. ln = tls.NewListener(ln, tlsconfig[0])
  380. }
  381. // Print startup message
  382. if !app.Settings.DisableStartupMessage {
  383. app.startupMessage(ln.Addr().String(), len(tlsconfig) > 0, "")
  384. }
  385. return app.server.Serve(ln)
  386. }
  387. // Listen serves HTTP requests from the given addr or port.
  388. // You can pass an optional *tls.Config to enable TLS.
  389. //
  390. // app.Listen(8080)
  391. // app.Listen("8080")
  392. // app.Listen(":8080")
  393. // app.Listen("127.0.0.1:8080")
  394. func (app *App) Listen(address interface{}, tlsconfig ...*tls.Config) error {
  395. // Convert address to string
  396. addr, ok := address.(string)
  397. if !ok {
  398. port, ok := address.(int)
  399. if !ok {
  400. return fmt.Errorf("listen: host must be an `int` port or `string` address")
  401. }
  402. addr = strconv.Itoa(port)
  403. }
  404. if !strings.Contains(addr, ":") {
  405. addr = ":" + addr
  406. }
  407. // Update server settings
  408. app.init()
  409. // Start prefork
  410. if app.Settings.Prefork {
  411. return app.prefork(addr, tlsconfig...)
  412. }
  413. // Set correct network protocol
  414. network := "tcp4"
  415. if isIPv6(addr) {
  416. network = "tcp6"
  417. }
  418. // Setup listener
  419. ln, err := net.Listen(network, addr)
  420. if err != nil {
  421. return err
  422. }
  423. // Add TLS config if provided
  424. if len(tlsconfig) > 0 {
  425. ln = tls.NewListener(ln, tlsconfig[0])
  426. }
  427. // Print startup message
  428. if !app.Settings.DisableStartupMessage {
  429. app.startupMessage(ln.Addr().String(), len(tlsconfig) > 0, "")
  430. }
  431. // Start listening
  432. return app.server.Serve(ln)
  433. }
  434. // Handler returns the server handler.
  435. func (app *App) Handler() fasthttp.RequestHandler {
  436. app.init()
  437. return app.handler
  438. }
  439. // Handler returns the server handler.
  440. func (app *App) Stack() [][]*Route {
  441. return app.stack
  442. }
  443. // Shutdown gracefully
  444. // shuts down the server without interrupting any active connections.
  445. // Shutdown works by first closing all open listeners and then waiting indefinitely for all connections to return to idle and then shut down.
  446. //
  447. // When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return nil.
  448. // Make sure the program doesn't exit and waits instead for Shutdown to return.
  449. //
  450. // Shutdown does not close keepalive connections so its recommended to set ReadTimeout to something else than 0.
  451. func (app *App) Shutdown() error {
  452. app.mutex.Lock()
  453. defer app.mutex.Unlock()
  454. if app.server == nil {
  455. return fmt.Errorf("shutdown: server is not running")
  456. }
  457. return app.server.Shutdown()
  458. }
  459. // Test is used for internal debugging by passing a *http.Request.
  460. // Timeout is optional and defaults to 1s, -1 will disable it completely.
  461. func (app *App) Test(request *http.Request, msTimeout ...int) (*http.Response, error) {
  462. timeout := 1000 // 1 second default
  463. if len(msTimeout) > 0 {
  464. timeout = msTimeout[0]
  465. }
  466. // Add Content-Length if not provided with body
  467. if request.Body != http.NoBody && request.Header.Get("Content-Length") == "" {
  468. request.Header.Add("Content-Length", strconv.FormatInt(request.ContentLength, 10))
  469. }
  470. // Dump raw http request
  471. dump, err := httputil.DumpRequest(request, true)
  472. if err != nil {
  473. return nil, err
  474. }
  475. // Update server settings
  476. app.init()
  477. // Create test connection
  478. conn := new(testConn)
  479. // Write raw http request
  480. if _, err = conn.r.Write(dump); err != nil {
  481. return nil, err
  482. }
  483. // Serve conn to server
  484. channel := make(chan error)
  485. go func() {
  486. channel <- app.server.ServeConn(conn)
  487. }()
  488. // Wait for callback
  489. if timeout >= 0 {
  490. // With timeout
  491. select {
  492. case err = <-channel:
  493. case <-time.After(time.Duration(timeout) * time.Millisecond):
  494. return nil, fmt.Errorf("test: timeout error %vms", timeout)
  495. }
  496. } else {
  497. // Without timeout
  498. err = <-channel
  499. }
  500. // Check for errors
  501. if err != nil {
  502. return nil, err
  503. }
  504. // Read response
  505. buffer := bufio.NewReader(&conn.w)
  506. // Convert raw http response to *http.Response
  507. resp, err := http.ReadResponse(buffer, request)
  508. if err != nil {
  509. return nil, err
  510. }
  511. // Return *http.Response
  512. return resp, nil
  513. }
  514. type disableLogger struct{}
  515. func (dl *disableLogger) Printf(format string, args ...interface{}) {
  516. // fmt.Println(fmt.Sprintf(format, args...))
  517. }
  518. func (app *App) init() *App {
  519. // Lock application
  520. app.mutex.Lock()
  521. defer app.mutex.Unlock()
  522. // Load view engine if provided
  523. if app.Settings != nil {
  524. // Only load templates if an view engine is specified
  525. if app.Settings.Views != nil {
  526. if err := app.Settings.Views.Load(); err != nil {
  527. fmt.Printf("views: %v\n", err)
  528. }
  529. }
  530. }
  531. if app.server == nil {
  532. app.server = &fasthttp.Server{
  533. Logger: &disableLogger{},
  534. LogAllErrors: false,
  535. ErrorHandler: func(fctx *fasthttp.RequestCtx, err error) {
  536. ctx := app.AcquireCtx(fctx)
  537. if _, ok := err.(*fasthttp.ErrSmallBuffer); ok {
  538. ctx.err = ErrRequestHeaderFieldsTooLarge
  539. } else if netErr, ok := err.(*net.OpError); ok && netErr.Timeout() {
  540. ctx.err = ErrRequestTimeout
  541. } else if len(err.Error()) == 33 && err.Error() == "body size exceeds the given limit" {
  542. ctx.err = ErrRequestEntityTooLarge
  543. } else {
  544. ctx.err = ErrBadRequest
  545. }
  546. app.Settings.ErrorHandler(ctx, ctx.err)
  547. app.ReleaseCtx(ctx)
  548. },
  549. }
  550. }
  551. if app.server.Handler == nil {
  552. app.server.Handler = app.handler
  553. }
  554. app.server.Name = app.Settings.ServerHeader
  555. app.server.Concurrency = app.Settings.Concurrency
  556. app.server.NoDefaultDate = app.Settings.DisableDefaultDate
  557. app.server.NoDefaultContentType = app.Settings.DisableDefaultContentType
  558. app.server.DisableHeaderNamesNormalizing = app.Settings.DisableHeaderNormalizing
  559. app.server.DisableKeepalive = app.Settings.DisableKeepalive
  560. app.server.MaxRequestBodySize = app.Settings.BodyLimit
  561. app.server.NoDefaultServerHeader = app.Settings.ServerHeader == ""
  562. app.server.ReadTimeout = app.Settings.ReadTimeout
  563. app.server.WriteTimeout = app.Settings.WriteTimeout
  564. app.server.IdleTimeout = app.Settings.IdleTimeout
  565. app.server.ReadBufferSize = app.Settings.ReadBufferSize
  566. app.server.WriteBufferSize = app.Settings.WriteBufferSize
  567. app.buildTree()
  568. return app
  569. }
  570. const (
  571. cBlack = "\u001b[90m"
  572. cRed = "\u001b[91m"
  573. // cGreen = "\u001b[92m"
  574. // cYellow = "\u001b[93m"
  575. // cBlue = "\u001b[94m"
  576. // cMagenta = "\u001b[95m"
  577. cCyan = "\u001b[96m"
  578. // cWhite = "\u001b[97m"
  579. cReset = "\u001b[0m"
  580. )
  581. func (app *App) startupMessage(addr string, tls bool, pids string) {
  582. // ignore child processes
  583. if app.IsChild() {
  584. return
  585. }
  586. // ascii logo
  587. var logo string
  588. logo += `%s _______ __ %s` + "\n"
  589. logo += `%s ____%s / ____(_) /_ ___ _____ %s` + "\n"
  590. logo += `%s_____%s / /_ / / __ \/ _ \/ ___/ %s` + "\n"
  591. logo += `%s __%s / __/ / / /_/ / __/ / %s` + "\n"
  592. logo += `%s /_/ /_/_.___/\___/_/%s %s` + ""
  593. logo += cRed + "v2 will be released on 15 September 2020!\nPlease visit https://gofiber.io/v2 for more information.\n" + cReset
  594. host, port := parseAddr(addr)
  595. padding := strconv.Itoa(len(host))
  596. if len(host) <= 4 {
  597. padding = "5"
  598. }
  599. var (
  600. tlsStr = "FALSE"
  601. preforkStr = "FALSE"
  602. handlerCount = strconv.Itoa(app.handlerCount)
  603. osName = utils.ToUpper(runtime.GOOS)
  604. cpuThreads = runtime.NumCPU()
  605. pid = os.Getpid()
  606. )
  607. if host == "" {
  608. host = "0.0.0.0"
  609. }
  610. if tls {
  611. tlsStr = "TRUE"
  612. }
  613. if app.Settings.Prefork {
  614. preforkStr = "TRUE"
  615. }
  616. // tabwriter makes sure the spacing are consistent across different values
  617. // colorable handles the escape sequence for stdout using ascii color codes
  618. host = fmt.Sprintf("%-"+padding+"s", host)
  619. port = fmt.Sprintf("%-"+padding+"s", port)
  620. tlsStr = fmt.Sprintf("%-"+padding+"s", tlsStr)
  621. handlerCount = fmt.Sprintf("%-"+padding+"s", handlerCount)
  622. app.out = colorable.NewColorableStdout()
  623. // Check if colors are supported
  624. if os.Getenv("TERM") == "dumb" ||
  625. (!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd())) {
  626. app.out = colorable.NewNonColorable(os.Stdout)
  627. }
  628. // simple Sprintf function that defaults back to black
  629. cyan := func(v interface{}) string {
  630. return fmt.Sprintf("%s%v%s", cCyan, v, cBlack)
  631. }
  632. // Build startup banner
  633. fmt.Fprintf(app.out, logo, cBlack, cBlack,
  634. cCyan, cBlack, fmt.Sprintf(" HOST %s OS %s", cyan(host), cyan(osName)),
  635. cCyan, cBlack, fmt.Sprintf(" PORT %s THREADS %s", cyan(port), cyan(cpuThreads)),
  636. cCyan, cBlack, fmt.Sprintf(" TLS %s PREFORK %s", cyan(tlsStr), cyan(preforkStr)),
  637. cBlack, cyan(Version), fmt.Sprintf(" HANDLERS %s PID %s%s%s\n", cyan(handlerCount), cyan(pid), pids, cReset),
  638. )
  639. }