2019-02-02 16:18:25 +08:00
|
|
|
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
2017-12-29 16:03:30 +08:00
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
2019-02-02 16:18:25 +08:00
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
2017-12-29 16:03:30 +08:00
|
|
|
|
2017-11-23 10:21:28 +08:00
|
|
|
package ghttp
|
|
|
|
|
|
|
|
import (
|
2019-06-19 09:06:52 +08:00
|
|
|
"bytes"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
2019-12-04 10:03:03 +08:00
|
|
|
"github.com/gogf/gf/debug/gdebug"
|
2020-03-04 17:29:23 +08:00
|
|
|
"github.com/gogf/gf/internal/intlog"
|
2019-06-22 11:03:50 +08:00
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"reflect"
|
|
|
|
"runtime"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2019-09-11 21:19:45 +08:00
|
|
|
"github.com/gogf/gf/os/gsession"
|
2019-08-22 21:04:30 +08:00
|
|
|
|
2019-07-29 21:01:19 +08:00
|
|
|
"github.com/gogf/gf/container/garray"
|
|
|
|
"github.com/gogf/gf/container/gmap"
|
|
|
|
"github.com/gogf/gf/container/gtype"
|
|
|
|
"github.com/gogf/gf/os/gcache"
|
|
|
|
"github.com/gogf/gf/os/genv"
|
|
|
|
"github.com/gogf/gf/os/gfile"
|
|
|
|
"github.com/gogf/gf/os/glog"
|
|
|
|
"github.com/gogf/gf/os/gproc"
|
|
|
|
"github.com/gogf/gf/os/gtimer"
|
|
|
|
"github.com/gogf/gf/text/gregex"
|
|
|
|
"github.com/gogf/gf/util/gconv"
|
2019-08-01 14:07:25 +08:00
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
"github.com/olekukonko/tablewriter"
|
2017-11-23 10:21:28 +08:00
|
|
|
)
|
|
|
|
|
2018-11-19 21:49:43 +08:00
|
|
|
type (
|
2020-01-21 17:18:03 +08:00
|
|
|
// Server wraps the http.Server and provides more feature.
|
2019-06-19 09:06:52 +08:00
|
|
|
Server struct {
|
2020-01-21 17:18:03 +08:00
|
|
|
name string // Unique name for instance management.
|
|
|
|
config ServerConfig // Configuration.
|
|
|
|
plugins []Plugin // Plugin array.
|
|
|
|
servers []*gracefulServer // Underlying http.Server array.
|
|
|
|
serverCount *gtype.Int // Underlying http.Server count.
|
|
|
|
closeChan chan struct{} // Used for underlying server closing event notification.
|
|
|
|
serveTree map[string]interface{} // The route map tree.
|
|
|
|
serveCache *gcache.Cache // Server cache for internal usage.
|
|
|
|
routesMap map[string][]registeredRouteItem // Route map mainly for route dumps and repeated route checks.
|
|
|
|
statusHandlerMap map[string]HandlerFunc // Custom status handler map.
|
|
|
|
sessionManager *gsession.Manager // Session manager.
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
|
2020-01-21 17:18:03 +08:00
|
|
|
// Router object.
|
2019-06-19 09:06:52 +08:00
|
|
|
Router struct {
|
2020-01-21 17:18:03 +08:00
|
|
|
Uri string // URI.
|
|
|
|
Method string // HTTP method
|
|
|
|
Domain string // Bound domain.
|
|
|
|
RegRule string // Parsed regular expression for route matching.
|
|
|
|
RegNames []string // Parsed router parameter names.
|
|
|
|
Priority int // Just for reference.
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
|
2020-01-21 17:18:03 +08:00
|
|
|
// Router item just for route dumps.
|
2019-12-04 13:55:08 +08:00
|
|
|
RouterItem struct {
|
2020-01-21 17:18:03 +08:00
|
|
|
Server string // Server name.
|
|
|
|
Address string // Listening address.
|
|
|
|
Domain string // Bound domain.
|
|
|
|
Type int // Router type.
|
|
|
|
Middleware string // Bound middleware.
|
|
|
|
Method string // Handler method name.
|
|
|
|
Route string // Route URI.
|
|
|
|
Priority int // Just for reference.
|
|
|
|
IsServiceHandler bool // Is service handler.
|
|
|
|
handler *handlerItem // The handler.
|
2019-12-04 13:55:08 +08:00
|
|
|
}
|
|
|
|
|
2020-01-21 17:18:03 +08:00
|
|
|
// handlerItem is the registered handler for route handling,
|
|
|
|
// including middleware and hook functions.
|
2019-06-19 09:06:52 +08:00
|
|
|
handlerItem struct {
|
2020-03-04 22:52:56 +08:00
|
|
|
itemId int // Unique handler item id mark.
|
2020-01-21 17:18:03 +08:00
|
|
|
itemName string // Handler name, which is automatically retrieved from runtime stack when registered.
|
|
|
|
itemType int // Handler type: object/handler/controller/middleware/hook.
|
|
|
|
itemFunc HandlerFunc // Handler address.
|
|
|
|
initFunc HandlerFunc // Initialization function when request enters the object(only available for object register type).
|
|
|
|
shutFunc HandlerFunc // Shutdown function when request leaves out the object(only available for object register type).
|
|
|
|
middleware []HandlerFunc // Bound middleware array.
|
|
|
|
ctrlInfo *handlerController // Controller information for reflect usage.
|
|
|
|
hookName string // Hook type name.
|
|
|
|
router *Router // Router object.
|
2020-03-17 14:48:52 +08:00
|
|
|
source string // Source file path:line when registering.
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
|
2020-01-21 17:18:03 +08:00
|
|
|
// handlerParsedItem is the item parsed from URL.Path.
|
2019-06-19 09:06:52 +08:00
|
|
|
handlerParsedItem struct {
|
2020-01-21 17:18:03 +08:00
|
|
|
handler *handlerItem // Handler information.
|
|
|
|
values map[string]string // Router values parsed from URL.Path.
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
|
2020-01-21 17:18:03 +08:00
|
|
|
// handlerController is the controller information used for reflect.
|
2019-08-03 15:54:12 +08:00
|
|
|
handlerController struct {
|
2020-01-21 17:18:03 +08:00
|
|
|
name string // Handler method name.
|
|
|
|
reflect reflect.Type // Reflect type of the controller.
|
2019-08-03 15:54:12 +08:00
|
|
|
}
|
|
|
|
|
2020-01-21 17:18:03 +08:00
|
|
|
// registeredRouteItem stores the information of the router and is used for route map.
|
2019-06-19 09:06:52 +08:00
|
|
|
registeredRouteItem struct {
|
2020-03-17 14:48:52 +08:00
|
|
|
source string // Source file path and its line number.
|
2020-01-21 17:18:03 +08:00
|
|
|
handler *handlerItem // Handler object.
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
|
2020-01-21 17:18:03 +08:00
|
|
|
// Request handler function.
|
2019-06-19 09:06:52 +08:00
|
|
|
HandlerFunc = func(r *Request)
|
|
|
|
|
2020-01-21 17:18:03 +08:00
|
|
|
// Listening file descriptor mapping.
|
|
|
|
// The key is either "http" or "https" and the value is its FD.
|
2019-06-19 09:06:52 +08:00
|
|
|
listenerFdMap = map[string]string
|
2018-11-19 21:49:43 +08:00
|
|
|
)
|
|
|
|
|
2018-08-01 13:04:15 +08:00
|
|
|
const (
|
2019-12-03 17:16:52 +08:00
|
|
|
SERVER_STATUS_STOPPED = 0
|
|
|
|
SERVER_STATUS_RUNNING = 1
|
|
|
|
HOOK_BEFORE_SERVE = "HOOK_BEFORE_SERVE"
|
|
|
|
HOOK_AFTER_SERVE = "HOOK_AFTER_SERVE"
|
|
|
|
HOOK_BEFORE_OUTPUT = "HOOK_BEFORE_OUTPUT"
|
|
|
|
HOOK_AFTER_OUTPUT = "HOOK_AFTER_OUTPUT"
|
2019-08-03 15:54:12 +08:00
|
|
|
HTTP_METHODS = "GET,PUT,POST,DELETE,PATCH,HEAD,CONNECT,OPTIONS,TRACE"
|
|
|
|
gDEFAULT_SERVER = "default"
|
|
|
|
gDEFAULT_DOMAIN = "default"
|
|
|
|
gDEFAULT_METHOD = "ALL"
|
|
|
|
gHANDLER_TYPE_HANDLER = 1
|
|
|
|
gHANDLER_TYPE_OBJECT = 2
|
|
|
|
gHANDLER_TYPE_CONTROLLER = 3
|
|
|
|
gHANDLER_TYPE_MIDDLEWARE = 4
|
|
|
|
gHANDLER_TYPE_HOOK = 5
|
|
|
|
gEXCEPTION_EXIT = "exit"
|
|
|
|
gEXCEPTION_EXIT_ALL = "exit_all"
|
|
|
|
gEXCEPTION_EXIT_HOOK = "exit_hook"
|
2019-12-01 14:24:56 +08:00
|
|
|
gROUTE_CACHE_DURATION = time.Hour
|
2017-12-11 17:16:59 +08:00
|
|
|
)
|
|
|
|
|
2018-11-19 21:49:43 +08:00
|
|
|
var (
|
2020-01-21 17:18:03 +08:00
|
|
|
// methodsMap stores all supported HTTP method,
|
|
|
|
// it is used for quick HTTP method searching using map.
|
2019-06-19 09:06:52 +08:00
|
|
|
methodsMap = make(map[string]struct{})
|
|
|
|
|
2020-03-04 17:29:23 +08:00
|
|
|
// serverMapping stores more than one server instances for current process.
|
2020-01-21 17:18:03 +08:00
|
|
|
// The key is the name of the server, and the value is its instance.
|
2019-07-23 23:20:27 +08:00
|
|
|
serverMapping = gmap.NewStrAnyMap(true)
|
2019-06-19 09:06:52 +08:00
|
|
|
|
2020-01-21 17:18:03 +08:00
|
|
|
// serverRunning marks the running server count.
|
|
|
|
// If there no successful server running or all servers shutdown, this value is 0.
|
2019-06-19 09:06:52 +08:00
|
|
|
serverRunning = gtype.NewInt()
|
|
|
|
|
2020-01-21 17:18:03 +08:00
|
|
|
// wsUpgrader is the default up-grader configuration for websocket.
|
2019-06-19 09:06:52 +08:00
|
|
|
wsUpgrader = websocket.Upgrader{
|
2020-01-21 17:18:03 +08:00
|
|
|
// It does not check the origin in default, the application can do it itself.
|
2019-06-19 09:06:52 +08:00
|
|
|
CheckOrigin: func(r *http.Request) bool {
|
|
|
|
return true
|
|
|
|
},
|
|
|
|
}
|
2020-01-21 17:18:03 +08:00
|
|
|
// allDoneChan is the event for all server have done its serving and exit.
|
|
|
|
// It is used for process blocking purpose.
|
2019-06-19 09:06:52 +08:00
|
|
|
allDoneChan = make(chan struct{}, 1000)
|
|
|
|
|
2020-01-21 17:18:03 +08:00
|
|
|
// serverProcessInited is used for lazy initialization for server.
|
|
|
|
// The process can only be initialized once.
|
2019-06-19 09:06:52 +08:00
|
|
|
serverProcessInited = gtype.NewBool()
|
|
|
|
|
2020-02-07 17:21:05 +08:00
|
|
|
// gracefulEnabled is used for graceful reload feature, which is false in default.
|
2020-02-07 16:29:14 +08:00
|
|
|
gracefulEnabled = false
|
2018-11-19 21:49:43 +08:00
|
|
|
)
|
2018-05-10 23:52:09 +08:00
|
|
|
|
2019-03-01 23:45:55 +08:00
|
|
|
func init() {
|
2020-01-21 17:18:03 +08:00
|
|
|
// Initialize the methods map.
|
2019-06-19 09:06:52 +08:00
|
|
|
for _, v := range strings.Split(HTTP_METHODS, ",") {
|
|
|
|
methodsMap[v] = struct{}{}
|
|
|
|
}
|
2019-03-01 23:45:55 +08:00
|
|
|
}
|
|
|
|
|
2020-04-29 00:14:29 +08:00
|
|
|
// SetGraceful enables/disables the graceful reload feature for server,
|
|
|
|
// which is false in default.
|
|
|
|
//
|
|
|
|
// Note that this feature switch is not for single server instance but for whole process.
|
2020-06-28 20:52:33 +08:00
|
|
|
// Deprecated, use configuration of ghttp.Server for controlling this feature.
|
2019-02-20 16:07:11 +08:00
|
|
|
func SetGraceful(enabled bool) {
|
2019-06-19 09:06:52 +08:00
|
|
|
gracefulEnabled = enabled
|
2019-02-20 16:07:11 +08:00
|
|
|
}
|
2018-07-31 22:55:54 +08:00
|
|
|
|
2020-04-29 00:14:29 +08:00
|
|
|
// serverProcessInit initializes some process configurations, which can only be done once.
|
2019-02-20 16:07:11 +08:00
|
|
|
func serverProcessInit() {
|
2019-11-07 16:40:34 +08:00
|
|
|
if !serverProcessInited.Cas(false, true) {
|
2019-06-19 09:06:52 +08:00
|
|
|
return
|
|
|
|
}
|
2020-04-29 00:14:29 +08:00
|
|
|
// This means it is a restart server, it should kill its parent before starting its listening,
|
|
|
|
// to avoid duplicated port listening in two processes.
|
2019-06-19 09:06:52 +08:00
|
|
|
if genv.Get(gADMIN_ACTION_RESTART_ENVKEY) != "" {
|
|
|
|
if p, e := os.FindProcess(gproc.PPid()); e == nil {
|
|
|
|
p.Kill()
|
|
|
|
p.Wait()
|
|
|
|
} else {
|
|
|
|
glog.Error(e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-29 00:14:29 +08:00
|
|
|
// Signal handler.
|
2019-06-19 09:06:52 +08:00
|
|
|
go handleProcessSignal()
|
2020-04-29 00:14:29 +08:00
|
|
|
|
|
|
|
// Process message handler.
|
|
|
|
// It's enabled only graceful feature is enabled.
|
2019-06-19 09:06:52 +08:00
|
|
|
if gracefulEnabled {
|
|
|
|
go handleProcessMessage()
|
|
|
|
}
|
|
|
|
|
2020-04-29 00:14:29 +08:00
|
|
|
// It's an ugly calling for better initializing the main package path
|
|
|
|
// in source development environment. It is useful only be used in main goroutine.
|
|
|
|
// It fails retrieving the main package path in asynchronized goroutines.
|
2019-06-19 09:06:52 +08:00
|
|
|
gfile.MainPkgPath()
|
2018-05-10 23:52:09 +08:00
|
|
|
}
|
|
|
|
|
2020-04-29 00:14:29 +08:00
|
|
|
// GetServer creates and returns a server instance using given name and default configurations.
|
|
|
|
// Note that the parameter <name> should be unique for different servers. It returns an existing
|
|
|
|
// server instance if given <name> is already existing in the server mapping.
|
2019-06-19 09:06:52 +08:00
|
|
|
func GetServer(name ...interface{}) *Server {
|
2019-09-04 19:23:19 +08:00
|
|
|
serverName := gDEFAULT_SERVER
|
2019-07-28 17:37:13 +08:00
|
|
|
if len(name) > 0 && name[0] != "" {
|
2019-09-04 19:23:19 +08:00
|
|
|
serverName = gconv.String(name[0])
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
2019-09-04 19:23:19 +08:00
|
|
|
if s := serverMapping.Get(serverName); s != nil {
|
2019-06-19 09:06:52 +08:00
|
|
|
return s.(*Server)
|
|
|
|
}
|
|
|
|
s := &Server{
|
2019-09-04 19:23:19 +08:00
|
|
|
name: serverName,
|
2020-01-21 17:18:03 +08:00
|
|
|
plugins: make([]Plugin, 0),
|
2019-06-19 09:06:52 +08:00
|
|
|
servers: make([]*gracefulServer, 0),
|
2019-11-28 23:19:37 +08:00
|
|
|
closeChan: make(chan struct{}, 10000),
|
2019-06-19 09:06:52 +08:00
|
|
|
serverCount: gtype.NewInt(),
|
|
|
|
statusHandlerMap: make(map[string]HandlerFunc),
|
|
|
|
serveTree: make(map[string]interface{}),
|
|
|
|
serveCache: gcache.New(),
|
|
|
|
routesMap: make(map[string][]registeredRouteItem),
|
|
|
|
}
|
2020-04-29 00:14:29 +08:00
|
|
|
// Initialize the server using default configurations.
|
|
|
|
if err := s.SetConfig(Config()); err != nil {
|
2019-11-07 11:32:25 +08:00
|
|
|
panic(err)
|
|
|
|
}
|
2020-04-29 00:14:29 +08:00
|
|
|
// Record the server to internal server mapping by name.
|
2019-09-04 19:23:19 +08:00
|
|
|
serverMapping.Set(serverName, s)
|
2019-06-19 09:06:52 +08:00
|
|
|
return s
|
2017-12-07 14:57:16 +08:00
|
|
|
}
|
|
|
|
|
2020-04-29 00:14:29 +08:00
|
|
|
// Start starts listening on configured port.
|
|
|
|
// This function does not block the process, you can use function Wait blocking the process.
|
2018-05-13 14:04:37 +08:00
|
|
|
func (s *Server) Start() error {
|
2019-12-04 13:55:08 +08:00
|
|
|
// Register group routes.
|
2019-08-06 20:40:04 +08:00
|
|
|
s.handlePreBindItems()
|
|
|
|
|
2019-12-04 13:55:08 +08:00
|
|
|
// Server process initialization, which can only be initialized once.
|
2019-06-19 09:06:52 +08:00
|
|
|
serverProcessInit()
|
|
|
|
|
2019-12-04 13:55:08 +08:00
|
|
|
// Server can only be run once.
|
2019-06-19 09:06:52 +08:00
|
|
|
if s.Status() == SERVER_STATUS_RUNNING {
|
2019-11-08 19:52:49 +08:00
|
|
|
return errors.New("[ghttp] server is already running")
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
|
2019-12-04 13:55:08 +08:00
|
|
|
// If there's no route registered and no static service enabled,
|
|
|
|
// it then returns an error of invalid usage of server.
|
2019-06-19 09:06:52 +08:00
|
|
|
if len(s.routesMap) == 0 && !s.config.FileServerEnabled {
|
2019-11-08 19:52:49 +08:00
|
|
|
return errors.New(`[ghttp] there's no route set or static feature enabled, did you forget import the router?`)
|
|
|
|
}
|
2019-12-04 13:55:08 +08:00
|
|
|
// Logging path setting check.
|
2019-11-08 19:52:49 +08:00
|
|
|
if s.config.LogPath != "" {
|
|
|
|
if err := s.config.Logger.SetPath(s.config.LogPath); err != nil {
|
|
|
|
return errors.New(fmt.Sprintf("[ghttp] set log path '%s' error: %v", s.config.LogPath, err))
|
|
|
|
}
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
2019-10-29 16:45:42 +08:00
|
|
|
// Default session storage.
|
|
|
|
if s.config.SessionStorage == nil {
|
2019-11-07 20:42:13 +08:00
|
|
|
path := ""
|
|
|
|
if s.config.SessionPath != "" {
|
|
|
|
path = gfile.Join(s.config.SessionPath, s.name)
|
|
|
|
if !gfile.Exists(path) {
|
|
|
|
if err := gfile.Mkdir(path); err != nil {
|
2019-11-08 19:52:49 +08:00
|
|
|
return errors.New(fmt.Sprintf("[ghttp] mkdir failed for '%s': %v", path, err))
|
2019-11-07 20:42:13 +08:00
|
|
|
}
|
2019-11-07 20:36:33 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
s.config.SessionStorage = gsession.NewStorageFile(path)
|
2019-10-29 16:45:42 +08:00
|
|
|
}
|
|
|
|
// Initialize session manager when start running.
|
2019-11-07 20:36:33 +08:00
|
|
|
s.sessionManager = gsession.New(
|
|
|
|
s.config.SessionMaxAge,
|
|
|
|
s.config.SessionStorage,
|
|
|
|
)
|
2019-10-29 16:45:42 +08:00
|
|
|
|
2019-11-07 16:40:34 +08:00
|
|
|
// PProf feature.
|
|
|
|
if s.config.PProfEnabled {
|
|
|
|
s.EnablePProf(s.config.PProfPattern)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Default HTTP handler.
|
2019-06-19 09:06:52 +08:00
|
|
|
if s.config.Handler == nil {
|
2020-04-04 22:46:52 +08:00
|
|
|
s.config.Handler = s
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
|
2020-01-21 17:18:03 +08:00
|
|
|
// Install external plugins.
|
|
|
|
for _, p := range s.plugins {
|
|
|
|
if err := p.Install(s); err != nil {
|
|
|
|
s.Logger().Fatal(err)
|
|
|
|
}
|
|
|
|
}
|
2020-01-21 22:18:49 +08:00
|
|
|
// Check the group routes again.
|
|
|
|
s.handlePreBindItems()
|
2020-01-21 17:18:03 +08:00
|
|
|
|
2019-11-07 16:40:34 +08:00
|
|
|
// Start the HTTP server.
|
2019-06-19 09:06:52 +08:00
|
|
|
reloaded := false
|
|
|
|
fdMapStr := genv.Get(gADMIN_ACTION_RELOAD_ENVKEY)
|
|
|
|
if len(fdMapStr) > 0 {
|
|
|
|
sfm := bufferToServerFdMap([]byte(fdMapStr))
|
|
|
|
if v, ok := sfm[s.name]; ok {
|
|
|
|
s.startServer(v)
|
|
|
|
reloaded = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !reloaded {
|
|
|
|
s.startServer(nil)
|
|
|
|
}
|
|
|
|
|
2019-12-04 13:55:08 +08:00
|
|
|
// If this is a child process, it then notifies its parent exit.
|
2019-06-19 09:06:52 +08:00
|
|
|
if gproc.IsChild() {
|
|
|
|
gtimer.SetTimeout(2*time.Second, func() {
|
|
|
|
if err := gproc.Send(gproc.PPid(), []byte("exit"), gADMIN_GPROC_COMM_GROUP); err != nil {
|
2019-12-09 21:53:44 +08:00
|
|
|
//glog.Error("[ghttp] server error in process communication:", err)
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2019-12-10 12:28:55 +08:00
|
|
|
s.dumpRouterMap()
|
2019-06-19 09:06:52 +08:00
|
|
|
return nil
|
2018-05-13 14:04:37 +08:00
|
|
|
}
|
2018-04-27 22:12:11 +08:00
|
|
|
|
2019-12-04 13:55:08 +08:00
|
|
|
// DumpRouterMap dumps the router map to the log.
|
2019-12-10 12:28:55 +08:00
|
|
|
func (s *Server) dumpRouterMap() {
|
2019-12-04 13:55:08 +08:00
|
|
|
if s.config.DumpRouterMap && len(s.routesMap) > 0 {
|
|
|
|
buffer := bytes.NewBuffer(nil)
|
|
|
|
table := tablewriter.NewWriter(buffer)
|
2019-12-19 15:14:05 +08:00
|
|
|
table.SetHeader([]string{"SERVER", "DOMAIN", "ADDRESS", "METHOD", "ROUTE", "HANDLER", "MIDDLEWARE"})
|
2019-12-04 13:55:08 +08:00
|
|
|
table.SetRowLine(true)
|
|
|
|
table.SetBorder(false)
|
|
|
|
table.SetCenterSeparator("|")
|
2018-10-17 16:56:50 +08:00
|
|
|
|
2019-12-10 12:28:55 +08:00
|
|
|
for _, item := range s.GetRouterArray() {
|
2019-12-19 15:14:05 +08:00
|
|
|
data := make([]string, 7)
|
2019-12-10 12:28:55 +08:00
|
|
|
data[0] = item.Server
|
2019-12-19 15:14:05 +08:00
|
|
|
data[1] = item.Domain
|
|
|
|
data[2] = item.Address
|
2019-12-10 12:28:55 +08:00
|
|
|
data[3] = item.Method
|
2019-12-19 15:14:05 +08:00
|
|
|
data[4] = item.Route
|
|
|
|
data[5] = item.handler.itemName
|
|
|
|
data[6] = item.Middleware
|
2019-12-10 12:28:55 +08:00
|
|
|
table.Append(data)
|
2019-12-04 13:55:08 +08:00
|
|
|
}
|
|
|
|
table.Render()
|
|
|
|
s.config.Logger.Header(false).Printf("\n%s", buffer.String())
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
2019-12-04 13:55:08 +08:00
|
|
|
}
|
2019-06-19 09:06:52 +08:00
|
|
|
|
2019-12-10 12:28:55 +08:00
|
|
|
// GetRouterArray retrieves and returns the router array.
|
2019-12-04 13:55:08 +08:00
|
|
|
// The key of the returned map is the domain of the server.
|
2019-12-10 12:28:55 +08:00
|
|
|
func (s *Server) GetRouterArray() []RouterItem {
|
2019-06-19 09:06:52 +08:00
|
|
|
m := make(map[string]*garray.SortedArray)
|
2019-12-09 21:53:44 +08:00
|
|
|
address := s.config.Address
|
|
|
|
if s.config.HTTPSAddr != "" {
|
|
|
|
if len(address) > 0 {
|
|
|
|
address += ","
|
|
|
|
}
|
|
|
|
address += "tls" + s.config.HTTPSAddr
|
|
|
|
}
|
2019-06-19 09:06:52 +08:00
|
|
|
for k, registeredItems := range s.routesMap {
|
|
|
|
array, _ := gregex.MatchString(`(.*?)%([A-Z]+):(.+)@(.+)`, k)
|
|
|
|
for index, registeredItem := range registeredItems {
|
2019-12-04 13:55:08 +08:00
|
|
|
item := RouterItem{
|
2019-12-09 21:53:44 +08:00
|
|
|
Server: s.name,
|
|
|
|
Address: address,
|
|
|
|
Domain: array[4],
|
2019-12-08 22:55:32 +08:00
|
|
|
Type: registeredItem.handler.itemType,
|
2019-12-04 13:55:08 +08:00
|
|
|
Middleware: array[1],
|
|
|
|
Method: array[2],
|
|
|
|
Route: array[3],
|
|
|
|
Priority: len(registeredItems) - index - 1,
|
2019-08-03 23:57:20 +08:00
|
|
|
handler: registeredItem.handler,
|
|
|
|
}
|
2019-12-09 23:19:39 +08:00
|
|
|
switch item.handler.itemType {
|
|
|
|
case gHANDLER_TYPE_CONTROLLER, gHANDLER_TYPE_OBJECT, gHANDLER_TYPE_HANDLER:
|
|
|
|
item.IsServiceHandler = true
|
|
|
|
case gHANDLER_TYPE_MIDDLEWARE:
|
2019-12-04 13:55:08 +08:00
|
|
|
item.Middleware = "GLOBAL MIDDLEWARE"
|
2019-12-04 10:03:03 +08:00
|
|
|
}
|
|
|
|
if len(item.handler.middleware) > 0 {
|
|
|
|
for _, v := range item.handler.middleware {
|
2019-12-04 13:55:08 +08:00
|
|
|
if item.Middleware != "" {
|
|
|
|
item.Middleware += ","
|
2019-12-04 10:03:03 +08:00
|
|
|
}
|
2019-12-04 13:55:08 +08:00
|
|
|
item.Middleware += gdebug.FuncName(v)
|
2019-12-04 10:03:03 +08:00
|
|
|
}
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
2019-12-04 10:03:03 +08:00
|
|
|
// If the domain does not exist in the dump map, it create the map.
|
|
|
|
// The value of the map is a custom sorted array.
|
2019-12-04 13:55:08 +08:00
|
|
|
if _, ok := m[item.Domain]; !ok {
|
2019-12-04 10:03:03 +08:00
|
|
|
// Sort in ASC order.
|
2019-12-10 12:28:55 +08:00
|
|
|
m[item.Domain] = garray.NewSortedArray(func(v1, v2 interface{}) int {
|
2019-12-04 13:55:08 +08:00
|
|
|
item1 := v1.(RouterItem)
|
|
|
|
item2 := v2.(RouterItem)
|
2019-06-19 09:06:52 +08:00
|
|
|
r := 0
|
2019-12-04 13:55:08 +08:00
|
|
|
if r = strings.Compare(item1.Domain, item2.Domain); r == 0 {
|
|
|
|
if r = strings.Compare(item1.Route, item2.Route); r == 0 {
|
|
|
|
if r = strings.Compare(item1.Method, item2.Method); r == 0 {
|
2019-08-03 23:57:20 +08:00
|
|
|
if item1.handler.itemType == gHANDLER_TYPE_MIDDLEWARE && item2.handler.itemType != gHANDLER_TYPE_MIDDLEWARE {
|
|
|
|
return -1
|
|
|
|
} else if item1.handler.itemType == gHANDLER_TYPE_MIDDLEWARE && item2.handler.itemType == gHANDLER_TYPE_MIDDLEWARE {
|
|
|
|
return 1
|
2019-12-04 13:55:08 +08:00
|
|
|
} else if r = strings.Compare(item1.Middleware, item2.Middleware); r == 0 {
|
|
|
|
r = item2.Priority - item1.Priority
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return r
|
2019-07-23 23:20:27 +08:00
|
|
|
})
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
2019-12-04 13:55:08 +08:00
|
|
|
m[item.Domain].Add(item)
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
}
|
2019-12-10 12:28:55 +08:00
|
|
|
routerArray := make([]RouterItem, 0, 128)
|
|
|
|
for _, array := range m {
|
|
|
|
for _, v := range array.Slice() {
|
|
|
|
routerArray = append(routerArray, v.(RouterItem))
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
}
|
2019-12-10 12:28:55 +08:00
|
|
|
return routerArray
|
2018-10-17 10:09:42 +08:00
|
|
|
}
|
|
|
|
|
2019-12-04 13:55:08 +08:00
|
|
|
// Run starts server listening in blocking way.
|
2020-03-04 17:29:23 +08:00
|
|
|
// It's commonly used for single server situation.
|
2019-06-22 11:03:50 +08:00
|
|
|
func (s *Server) Run() {
|
2019-06-19 09:06:52 +08:00
|
|
|
if err := s.Start(); err != nil {
|
2020-01-21 15:42:08 +08:00
|
|
|
s.Logger().Fatal(err)
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
2019-12-04 13:55:08 +08:00
|
|
|
// Blocking using channel.
|
2019-06-19 09:06:52 +08:00
|
|
|
<-s.closeChan
|
2020-03-04 17:29:23 +08:00
|
|
|
// Remove plugins.
|
|
|
|
if len(s.plugins) > 0 {
|
|
|
|
for _, p := range s.plugins {
|
|
|
|
intlog.Printf(`remove plugin: %s`, p.Name())
|
|
|
|
p.Remove()
|
|
|
|
}
|
|
|
|
}
|
2020-01-21 15:42:08 +08:00
|
|
|
s.Logger().Printf("[ghttp] %d: all servers shutdown", gproc.Pid())
|
2018-05-10 19:16:41 +08:00
|
|
|
}
|
2018-05-10 17:48:47 +08:00
|
|
|
|
2019-12-04 13:55:08 +08:00
|
|
|
// Wait blocks to wait for all servers done.
|
|
|
|
// It's commonly used in multiple servers situation.
|
2018-05-13 14:04:37 +08:00
|
|
|
func Wait() {
|
2019-06-19 09:06:52 +08:00
|
|
|
<-allDoneChan
|
2020-03-04 17:29:23 +08:00
|
|
|
// Remove plugins.
|
|
|
|
serverMapping.Iterator(func(k string, v interface{}) bool {
|
|
|
|
s := v.(*Server)
|
|
|
|
if len(s.plugins) > 0 {
|
|
|
|
for _, p := range s.plugins {
|
|
|
|
intlog.Printf(`remove plugin: %s`, p.Name())
|
|
|
|
p.Remove()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
})
|
2019-11-08 19:52:49 +08:00
|
|
|
glog.Printf("[ghttp] %d: all servers shutdown", gproc.Pid())
|
2018-05-13 14:04:37 +08:00
|
|
|
}
|
|
|
|
|
2020-04-29 00:14:29 +08:00
|
|
|
// startServer starts the underlying server listening.
|
2018-05-10 23:52:09 +08:00
|
|
|
func (s *Server) startServer(fdMap listenerFdMap) {
|
2019-06-19 09:06:52 +08:00
|
|
|
var httpsEnabled bool
|
2020-04-29 00:14:29 +08:00
|
|
|
// HTTPS
|
2019-11-07 16:40:34 +08:00
|
|
|
if s.config.TLSConfig != nil || (s.config.HTTPSCertPath != "" && s.config.HTTPSKeyPath != "") {
|
2019-06-19 09:06:52 +08:00
|
|
|
if len(s.config.HTTPSAddr) == 0 {
|
2019-11-07 11:32:25 +08:00
|
|
|
if len(s.config.Address) > 0 {
|
|
|
|
s.config.HTTPSAddr = s.config.Address
|
|
|
|
s.config.Address = ""
|
2019-06-19 09:06:52 +08:00
|
|
|
} else {
|
|
|
|
s.config.HTTPSAddr = gDEFAULT_HTTPS_ADDR
|
|
|
|
}
|
|
|
|
}
|
|
|
|
httpsEnabled = len(s.config.HTTPSAddr) > 0
|
|
|
|
var array []string
|
|
|
|
if v, ok := fdMap["https"]; ok && len(v) > 0 {
|
|
|
|
array = strings.Split(v, ",")
|
|
|
|
} else {
|
|
|
|
array = strings.Split(s.config.HTTPSAddr, ",")
|
|
|
|
}
|
|
|
|
for _, v := range array {
|
|
|
|
if len(v) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
fd := 0
|
2019-08-03 15:54:12 +08:00
|
|
|
itemFunc := v
|
2019-06-19 09:06:52 +08:00
|
|
|
array := strings.Split(v, "#")
|
|
|
|
if len(array) > 1 {
|
2019-08-03 15:54:12 +08:00
|
|
|
itemFunc = array[0]
|
2020-04-29 00:14:29 +08:00
|
|
|
// The windows OS does not support socket file descriptor passing
|
|
|
|
// from parent process.
|
2019-06-19 09:06:52 +08:00
|
|
|
if runtime.GOOS != "windows" {
|
|
|
|
fd = gconv.Int(array[1])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if fd > 0 {
|
2019-08-03 15:54:12 +08:00
|
|
|
s.servers = append(s.servers, s.newGracefulServer(itemFunc, fd))
|
2019-06-19 09:06:52 +08:00
|
|
|
} else {
|
2019-08-03 15:54:12 +08:00
|
|
|
s.servers = append(s.servers, s.newGracefulServer(itemFunc))
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
s.servers[len(s.servers)-1].isHttps = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// HTTP
|
2019-11-07 11:32:25 +08:00
|
|
|
if !httpsEnabled && len(s.config.Address) == 0 {
|
|
|
|
s.config.Address = gDEFAULT_HTTP_ADDR
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
var array []string
|
|
|
|
if v, ok := fdMap["http"]; ok && len(v) > 0 {
|
|
|
|
array = strings.Split(v, ",")
|
|
|
|
} else {
|
2019-11-07 11:32:25 +08:00
|
|
|
array = strings.Split(s.config.Address, ",")
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
for _, v := range array {
|
|
|
|
if len(v) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
fd := 0
|
2019-08-03 15:54:12 +08:00
|
|
|
itemFunc := v
|
2019-06-19 09:06:52 +08:00
|
|
|
array := strings.Split(v, "#")
|
|
|
|
if len(array) > 1 {
|
2019-08-03 15:54:12 +08:00
|
|
|
itemFunc = array[0]
|
2020-04-29 00:14:29 +08:00
|
|
|
// The windows OS does not support socket file descriptor passing
|
|
|
|
// from parent process.
|
2019-06-19 09:06:52 +08:00
|
|
|
if runtime.GOOS != "windows" {
|
|
|
|
fd = gconv.Int(array[1])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if fd > 0 {
|
2019-08-03 15:54:12 +08:00
|
|
|
s.servers = append(s.servers, s.newGracefulServer(itemFunc, fd))
|
2019-06-19 09:06:52 +08:00
|
|
|
} else {
|
2019-08-03 15:54:12 +08:00
|
|
|
s.servers = append(s.servers, s.newGracefulServer(itemFunc))
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
}
|
2020-04-29 00:14:29 +08:00
|
|
|
// Start listening asynchronizedly.
|
2019-06-19 09:06:52 +08:00
|
|
|
serverRunning.Add(1)
|
|
|
|
for _, v := range s.servers {
|
|
|
|
go func(server *gracefulServer) {
|
|
|
|
s.serverCount.Add(1)
|
|
|
|
err := (error)(nil)
|
|
|
|
if server.isHttps {
|
2019-11-07 16:40:34 +08:00
|
|
|
err = server.ListenAndServeTLS(s.config.HTTPSCertPath, s.config.HTTPSKeyPath, s.config.TLSConfig)
|
2019-06-19 09:06:52 +08:00
|
|
|
} else {
|
|
|
|
err = server.ListenAndServe()
|
|
|
|
}
|
2020-04-29 00:14:29 +08:00
|
|
|
// The process exits if the server is closed with none closing error.
|
2019-06-19 09:06:52 +08:00
|
|
|
if err != nil && !strings.EqualFold(http.ErrServerClosed.Error(), err.Error()) {
|
2020-01-21 15:42:08 +08:00
|
|
|
s.Logger().Fatal(err)
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
2020-04-29 00:14:29 +08:00
|
|
|
// If all the underlying servers shutdown, the process exits.
|
2019-06-19 09:06:52 +08:00
|
|
|
if s.serverCount.Add(-1) < 1 {
|
|
|
|
s.closeChan <- struct{}{}
|
|
|
|
if serverRunning.Add(-1) < 1 {
|
|
|
|
serverMapping.Remove(s.name)
|
|
|
|
allDoneChan <- struct{}{}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}(v)
|
|
|
|
}
|
2018-08-01 13:04:15 +08:00
|
|
|
}
|
2018-04-23 19:22:59 +08:00
|
|
|
|
2020-04-29 00:14:29 +08:00
|
|
|
// Status retrieves and returns the server status.
|
2018-08-01 13:04:15 +08:00
|
|
|
func (s *Server) Status() int {
|
2019-06-19 09:06:52 +08:00
|
|
|
if serverRunning.Val() == 0 {
|
|
|
|
return SERVER_STATUS_STOPPED
|
|
|
|
}
|
2020-04-29 00:14:29 +08:00
|
|
|
// If any underlying server is running, the server status is running.
|
2019-06-19 09:06:52 +08:00
|
|
|
for _, v := range s.servers {
|
|
|
|
if v.status == SERVER_STATUS_RUNNING {
|
|
|
|
return SERVER_STATUS_RUNNING
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return SERVER_STATUS_STOPPED
|
2018-05-08 23:38:09 +08:00
|
|
|
}
|
|
|
|
|
2020-04-29 00:14:29 +08:00
|
|
|
// getListenerFdMap retrieves and returns the socket file descriptors.
|
|
|
|
// The key of the returned map is "http" and "https".
|
2018-05-10 23:52:09 +08:00
|
|
|
func (s *Server) getListenerFdMap() map[string]string {
|
2019-06-19 09:06:52 +08:00
|
|
|
m := map[string]string{
|
|
|
|
"https": "",
|
|
|
|
"http": "",
|
|
|
|
}
|
|
|
|
for _, v := range s.servers {
|
2020-04-30 20:37:09 +08:00
|
|
|
str := v.address + "#" + gconv.String(v.Fd()) + ","
|
2019-06-19 09:06:52 +08:00
|
|
|
if v.isHttps {
|
2020-04-29 00:14:29 +08:00
|
|
|
if len(m["https"]) > 0 {
|
|
|
|
m["https"] += ","
|
|
|
|
}
|
2019-06-19 09:06:52 +08:00
|
|
|
m["https"] += str
|
|
|
|
} else {
|
2020-04-29 00:14:29 +08:00
|
|
|
if len(m["http"]) > 0 {
|
|
|
|
m["http"] += ","
|
|
|
|
}
|
2019-06-19 09:06:52 +08:00
|
|
|
m["http"] += str
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return m
|
2018-05-10 19:16:41 +08:00
|
|
|
}
|
2020-04-29 00:14:29 +08:00
|
|
|
|
|
|
|
// IsExitError checks if given error is an exit error of server.
|
|
|
|
// This is used in old version of server for custom error handler.
|
|
|
|
// Deprecated.
|
|
|
|
func IsExitError(err interface{}) bool {
|
|
|
|
errStr := gconv.String(err)
|
|
|
|
if strings.EqualFold(errStr, gEXCEPTION_EXIT) ||
|
|
|
|
strings.EqualFold(errStr, gEXCEPTION_EXIT_ALL) ||
|
|
|
|
strings.EqualFold(errStr, gEXCEPTION_EXIT_HOOK) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|