gf/g/net/ghttp/http_server.go

433 lines
14 KiB
Go
Raw Normal View History

2017-12-29 16:03:30 +08:00
// Copyright 2017 gf Author(https://gitee.com/johng/gf). All Rights Reserved.
//
// 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,
// You can obtain one at https://gitee.com/johng/gf.
2017-11-23 10:21:28 +08:00
package ghttp
import (
"strings"
"time"
"log"
2017-12-07 14:57:16 +08:00
"sync"
"errors"
"reflect"
2017-12-26 11:46:48 +08:00
"strconv"
"net/http"
"crypto/tls"
"path/filepath"
"gitee.com/johng/gf/g/util/gutil"
2017-12-28 15:21:25 +08:00
"gitee.com/johng/gf/g/net/grouter"
"gitee.com/johng/gf/g/util/gidgen"
"gitee.com/johng/gf/g/container/gmap"
2017-11-23 10:21:28 +08:00
)
const (
gDEFAULT_SERVER = "default"
gDEFAULT_DOMAIN = "default"
gDEFAULT_METHOD = "all"
gHTTP_METHODS = "GET,PUT,POST,DELETE,PATCH,HEAD,CONNECT,OPTIONS,TRACE"
)
2017-12-07 14:57:16 +08:00
// http server结构体
type Server struct {
2017-12-26 11:46:48 +08:00
hmu sync.RWMutex // handlerMap互斥锁
name string // 服务名称,方便识别
server http.Server // 底层http server对象
config ServerConfig // 配置对象
status int8 // 当前服务器状态(0未启动1运行中)
handlerMap HandlerMap // 所有注册的回调函数
methodsMap map[string]bool // 所有支持的HTTP Method
idgen *gidgen.Gen // 请求ID生成器
2017-12-28 15:21:25 +08:00
Router *grouter.Router // 路由管理对象
2017-12-07 14:57:16 +08:00
}
// 域名、URI与回调函数的绑定记录表
2017-12-26 10:13:49 +08:00
type HandlerMap map[string]HandlerItem
// http回调函数注册信息
2017-12-26 10:13:49 +08:00
type HandlerItem struct {
ctype reflect.Type // 控制器类型
fname string // 回调方法名称
2017-12-26 10:13:49 +08:00
faddr HandlerFunc // 准确的执行方法内存地址(与以上两个参数二选一)
}
2017-12-07 14:57:16 +08:00
2017-12-26 10:13:49 +08:00
// http注册函数
type HandlerFunc func(*Request)
2017-12-26 10:13:49 +08:00
2017-12-08 12:03:21 +08:00
// Server表用以存储和检索名称与Server对象之间的关联关系
var serverMapping = gmap.NewStringInterfaceMap()
2017-12-07 17:34:51 +08:00
// 获取/创建一个默认配置的HTTP Server(默认监听端口是80)
// 单例模式请保证name的唯一性
2017-12-30 18:35:24 +08:00
func GetServer(names...string) (*Server) {
name := gDEFAULT_SERVER
if len(names) > 0 {
name = names[0]
}
2017-12-08 12:03:21 +08:00
if s := serverMapping.Get(name); s != nil {
return s.(*Server)
2017-12-07 17:34:51 +08:00
}
2017-12-30 17:09:00 +08:00
s := &Server{
name : name,
handlerMap : make(HandlerMap),
methodsMap : make(map[string]bool),
idgen : gidgen.New(20000),
2017-12-30 17:09:00 +08:00
Router : grouter.New(),
}
2017-12-26 11:46:48 +08:00
for _, v := range strings.Split(gHTTP_METHODS, ",") {
s.methodsMap[v] = true
}
2017-12-08 12:03:21 +08:00
s.SetConfig(defaultServerConfig)
serverMapping.Set(name, s)
return s
2017-12-07 14:57:16 +08:00
}
2017-11-23 10:21:28 +08:00
// 执行
2017-12-07 17:34:51 +08:00
func (s *Server) Run() error {
2017-12-08 12:03:21 +08:00
if s.status == 1 {
return errors.New("server is already running")
}
2017-11-23 10:21:28 +08:00
// 底层http server配置
if s.config.Handler == nil {
s.config.Handler = http.HandlerFunc(s.defaultHttpHandle)
}
2017-12-07 14:57:16 +08:00
// 底层http server初始化
2017-11-23 10:21:28 +08:00
s.server = http.Server {
Addr : s.config.Addr,
Handler : s.config.Handler,
ReadTimeout : s.config.ReadTimeout,
WriteTimeout : s.config.WriteTimeout,
IdleTimeout : s.config.IdleTimeout,
MaxHeaderBytes : s.config.MaxHeaderBytes,
}
// 执行端口监听
2017-12-07 14:57:16 +08:00
if err := s.server.ListenAndServe(); err != nil {
return err
2017-11-23 10:21:28 +08:00
}
2017-12-07 17:34:51 +08:00
s.status = 1
2017-12-07 14:57:16 +08:00
return nil
2017-11-23 10:21:28 +08:00
}
// 获取
func (s *Server) GetName() string {
return s.name
}
2017-11-23 10:21:28 +08:00
// http server setting设置
// 注意使用该方法进行http server配置时需要配置所有的配置项否则没有配置的属性将会默认变量为空
2017-12-07 17:34:51 +08:00
func (s *Server)SetConfig(c ServerConfig) error {
if s.status == 1 {
return errors.New("server config cannot be changed while running")
}
2017-11-23 10:21:28 +08:00
if c.Handler == nil {
c.Handler = http.HandlerFunc(s.defaultHttpHandle)
}
s.config = c
// 需要处理server root最后的目录分隔符号
if s.config.ServerRoot != "" {
s.SetServerRoot(s.config.ServerRoot)
}
// 必需设置默认值的属性
if len(s.config.IndexFiles) < 1 {
s.SetIndexFiles(defaultServerConfig.IndexFiles)
}
if s.config.ServerAgent == "" {
s.SetServerAgent(defaultServerConfig.ServerAgent)
}
2017-12-07 17:34:51 +08:00
return nil
2017-11-23 10:21:28 +08:00
}
// 设置http server参数 - Addr
2017-12-25 17:29:06 +08:00
func (s *Server)SetAddr(addr string) error {
if s.status == 1 {
return errors.New("server config cannot be changed while running")
}
s.config.Addr = addr
return nil
}
// 设置http server参数 - Port
2017-12-19 17:33:12 +08:00
func (s *Server)SetPort(port int) error {
2017-12-07 17:34:51 +08:00
if s.status == 1 {
return errors.New("server config cannot be changed while running")
}
2017-12-19 17:33:12 +08:00
s.config.Addr = ":" + strconv.Itoa(port)
2017-12-07 17:34:51 +08:00
return nil
2017-11-23 10:21:28 +08:00
}
// 设置http server参数 - TLSConfig
2017-12-07 17:34:51 +08:00
func (s *Server)SetTLSConfig(tls *tls.Config) error {
if s.status == 1 {
return errors.New("server config cannot be changed while running")
}
2017-11-23 10:21:28 +08:00
s.config.TLSConfig = tls
2017-12-07 17:34:51 +08:00
return nil
2017-11-23 10:21:28 +08:00
}
// 设置http server参数 - ReadTimeout
2017-12-07 17:34:51 +08:00
func (s *Server)SetReadTimeout(t time.Duration) error {
if s.status == 1 {
return errors.New("server config cannot be changed while running")
}
2017-11-23 10:21:28 +08:00
s.config.ReadTimeout = t
2017-12-07 17:34:51 +08:00
return nil
2017-11-23 10:21:28 +08:00
}
// 设置http server参数 - WriteTimeout
2017-12-07 17:34:51 +08:00
func (s *Server)SetWriteTimeout(t time.Duration) error {
if s.status == 1 {
return errors.New("server config cannot be changed while running")
}
2017-11-23 10:21:28 +08:00
s.config.WriteTimeout = t
2017-12-07 17:34:51 +08:00
return nil
2017-11-23 10:21:28 +08:00
}
// 设置http server参数 - IdleTimeout
2017-12-07 17:34:51 +08:00
func (s *Server)SetIdleTimeout(t time.Duration) error {
if s.status == 1 {
return errors.New("server config cannot be changed while running")
}
2017-11-23 10:21:28 +08:00
s.config.IdleTimeout = t
2017-12-07 17:34:51 +08:00
return nil
2017-11-23 10:21:28 +08:00
}
// 设置http server参数 - MaxHeaderBytes
2017-12-07 17:34:51 +08:00
func (s *Server)SetMaxHeaderBytes(b int) error {
if s.status == 1 {
return errors.New("server config cannot be changed while running")
}
2017-11-23 10:21:28 +08:00
s.config.MaxHeaderBytes = b
2017-12-07 17:34:51 +08:00
return nil
2017-11-23 10:21:28 +08:00
}
// 设置http server参数 - ErrorLog
2017-12-07 17:34:51 +08:00
func (s *Server)SetErrorLog(logger *log.Logger) error {
if s.status == 1 {
return errors.New("server config cannot be changed while running")
}
2017-11-23 10:21:28 +08:00
s.config.ErrorLog = logger
2017-12-07 17:34:51 +08:00
return nil
2017-11-23 10:21:28 +08:00
}
// 设置http server参数 - IndexFiles
2017-12-07 17:34:51 +08:00
func (s *Server)SetIndexFiles(index []string) error {
if s.status == 1 {
return errors.New("server config cannot be changed while running")
}
2017-11-23 10:21:28 +08:00
s.config.IndexFiles = index
2017-12-07 17:34:51 +08:00
return nil
2017-11-23 10:21:28 +08:00
}
// 设置http server参数 - IndexFolder
2017-12-07 17:34:51 +08:00
func (s *Server)SetIndexFolder(index bool) error {
if s.status == 1 {
return errors.New("server config cannot be changed while running")
}
2017-11-23 10:21:28 +08:00
s.config.IndexFolder = index
2017-12-07 17:34:51 +08:00
return nil
2017-11-23 10:21:28 +08:00
}
// 设置http server参数 - ServerAgent
2017-12-07 17:34:51 +08:00
func (s *Server)SetServerAgent(agent string) error {
if s.status == 1 {
return errors.New("server config cannot be changed while running")
}
2017-11-23 10:21:28 +08:00
s.config.ServerAgent = agent
2017-12-07 17:34:51 +08:00
return nil
2017-11-23 10:21:28 +08:00
}
// 设置http server参数 - ServerRoot
2017-12-07 17:34:51 +08:00
func (s *Server)SetServerRoot(root string) error {
if s.status == 1 {
return errors.New("server config cannot be changed while running")
}
2017-11-23 10:21:28 +08:00
s.config.ServerRoot = strings.TrimRight(root, string(filepath.Separator))
2017-12-07 17:34:51 +08:00
return nil
2017-11-23 10:21:28 +08:00
}
// 生成回调方法查询的Key
func (s *Server) handlerKey(domain, method, pattern string) string {
return strings.ToUpper(method) + ":" + pattern + "@" + strings.ToLower(domain)
}
// 设置请求处理方法
2017-12-26 10:13:49 +08:00
func (s *Server) setHandler(domain, method, pattern string, hitem HandlerItem) {
s.hmu.Lock()
defer s.hmu.Unlock()
2017-12-13 11:36:29 +08:00
if method == gDEFAULT_METHOD {
2017-12-26 11:46:48 +08:00
for v, _ := range s.methodsMap {
s.handlerMap[s.handlerKey(domain, v, pattern)] = hitem
}
} else {
2017-12-26 10:13:49 +08:00
s.handlerMap[s.handlerKey(domain, method, pattern)] = hitem
}
}
// 查询请求处理方法
2017-12-26 10:13:49 +08:00
func (s *Server) getHandler(domain, method, pattern string) *HandlerItem {
s.hmu.RLock()
defer s.hmu.RUnlock()
key := s.handlerKey(domain, method, pattern)
if f, ok := s.handlerMap[key]; ok {
return &f
}
return nil
}
2017-11-23 10:21:28 +08:00
// 绑定URI到操作函数/方法
// pattern的格式形如/user/list, put:/user, delete:/user, post:/user@johng.cn
2017-11-23 10:21:28 +08:00
// 支持RESTful的请求格式具体业务逻辑由绑定的处理方法来执行
2017-12-26 10:13:49 +08:00
func (s *Server)bindHandlerItem(pattern string, hitem HandlerItem) error {
2017-12-07 17:34:51 +08:00
if s.status == 1 {
return errors.New("server handlers cannot be changed while running")
}
uri := ""
domain := gDEFAULT_DOMAIN
2017-12-11 18:21:30 +08:00
method := "all"
result := strings.Split(pattern, "@")
if len(result) > 1 {
domain = result[1]
2017-11-23 10:21:28 +08:00
}
result = strings.Split(result[0], ":")
2017-11-23 10:21:28 +08:00
if len(result) > 1 {
method = result[0]
2017-12-26 11:46:48 +08:00
uri = result[1]
2017-11-23 10:21:28 +08:00
} else {
uri = result[0]
2017-11-23 10:21:28 +08:00
}
if uri == "" {
return errors.New("invalid pattern")
2017-11-23 10:21:28 +08:00
}
2017-12-26 10:13:49 +08:00
s.setHandler(domain, method, uri, hitem)
2017-12-07 14:57:16 +08:00
return nil
2017-11-23 10:21:28 +08:00
}
// 通过映射数组绑定URI到操作函数/方法
func (s *Server)bindHandlerByMap(m HandlerMap) error {
for p, h := range m {
2017-12-26 10:13:49 +08:00
if err := s.bindHandlerItem(p, h); err != nil {
return err
}
2017-11-23 10:21:28 +08:00
}
return nil
2017-11-23 10:21:28 +08:00
}
2017-12-26 11:46:48 +08:00
// 将方法名称按照设定的规则转换为URI并附加到指定的URI后面
2017-12-30 18:35:24 +08:00
func (s *Server)appendMethodNameToUriWithPattern(pattern string, name string) string {
// 检测域名后缀
array := strings.Split(pattern, "@")
// 分离URI(其实可能包含HTTP Method)
uri := array[0]
2017-12-26 11:46:48 +08:00
uri = strings.TrimRight(uri, "/") + "/"
// 方法名中间存在大写字母转换为小写URI地址以“-”号链接每个单词
for i := 0; i < len(name); i++ {
if i > 0 && gutil.IsLetterUpper(name[i]) {
uri += "-"
}
uri += strings.ToLower(string(name[i]))
}
2017-12-30 18:35:24 +08:00
// 加上指定域名后缀
if len(array) > 1 {
uri += "@" + array[1]
}
2017-12-26 11:46:48 +08:00
return uri
}
2017-12-30 18:35:24 +08:00
// 注意该方法是直接绑定函数的内存地址,执行的时候直接执行该方法,不会存在初始化新的控制器逻辑
2017-12-26 10:13:49 +08:00
func (s *Server)BindHandler(pattern string, handler HandlerFunc) error {
return s.bindHandlerItem(pattern, HandlerItem{nil, "", handler})
2017-11-23 10:21:28 +08:00
}
2017-12-26 11:46:48 +08:00
// 绑定对象到URI请求处理中会自动识别方法名称并附加到对应的URI地址后面
// 需要注意对象方法的定义必须按照ghttp.HandlerFunc来定义
2017-12-30 18:35:24 +08:00
func (s *Server)BindObject(pattern string, obj interface{}) error {
2017-12-26 11:46:48 +08:00
m := make(HandlerMap)
v := reflect.ValueOf(obj)
t := v.Type()
for i := 0; i < v.NumMethod(); i++ {
name := t.Method(i).Name
2017-12-30 18:35:24 +08:00
key := s.appendMethodNameToUriWithPattern(pattern, name)
m[key] = HandlerItem{nil, "", v.Method(i).Interface().(func(*Request))}
2017-12-26 11:46:48 +08:00
}
return s.bindHandlerByMap(m)
}
// 绑定对象到URI请求处理中会自动识别方法名称并附加到对应的URI地址后面
// 需要注意对象方法的定义必须按照ghttp.HandlerFunc来定义
2017-12-30 18:35:24 +08:00
func (s *Server)BindObjectRest(pattern string, obj interface{}) error {
2017-12-26 11:46:48 +08:00
m := make(HandlerMap)
v := reflect.ValueOf(obj)
t := v.Type()
for i := 0; i < v.NumMethod(); i++ {
name := t.Method(i).Name
if _, ok := s.methodsMap[strings.ToUpper(name)]; !ok {
continue
}
2017-12-30 18:35:24 +08:00
key := name + ":" + pattern
m[key] = HandlerItem{nil, "", v.Method(i).Interface().(func(*Request))}
2017-12-26 11:46:48 +08:00
}
return s.bindHandlerByMap(m)
}
// 绑定控制器控制器需要实现gmvc.Controller接口
2017-12-26 10:13:49 +08:00
// 这种方式绑定的控制器每一次请求都会初始化一个新的控制器对象进行处理,对应不同的请求会话
2017-12-30 18:35:24 +08:00
func (s *Server)BindController(pattern string, c Controller) error {
// 遍历控制器获取方法列表并构造成uri
m := make(HandlerMap)
v := reflect.ValueOf(c)
t := v.Type()
for i := 0; i < v.NumMethod(); i++ {
name := t.Method(i).Name
if name == "Init" || name == "Shut" {
continue
}
2017-12-30 18:35:24 +08:00
key := s.appendMethodNameToUriWithPattern(pattern, name)
2017-12-26 11:46:48 +08:00
m[key] = HandlerItem{v.Elem().Type(), name, nil}
}
return s.bindHandlerByMap(m)
}
2017-12-30 18:35:24 +08:00
// 绑定控制器(RESTFul)控制器需要实现gmvc.Controller接口
2017-12-26 11:46:48 +08:00
// 方法会识别HTTP方法并做REST绑定处理例如Post方法会绑定到HTTP POST的方法请求处理Delete方法会绑定到HTTP DELETE的方法请求处理
// 因此只会绑定HTTP Method对应的方法其他方法不会自动注册绑定
// 这种方式绑定的控制器每一次请求都会初始化一个新的控制器对象进行处理,对应不同的请求会话
2017-12-30 18:35:24 +08:00
func (s *Server)BindControllerRest(pattern string, c Controller) error {
2017-12-26 11:46:48 +08:00
// 遍历控制器获取方法列表并构造成uri
m := make(HandlerMap)
v := reflect.ValueOf(c)
t := v.Type()
methods := make(map[string]bool)
for _, v := range strings.Split(gHTTP_METHODS, ",") {
methods[v] = true
}
for i := 0; i < v.NumMethod(); i++ {
name := t.Method(i).Name
if name == "Init" || name == "Shut" {
continue
}
if _, ok := s.methodsMap[strings.ToUpper(name)]; !ok {
continue
}
2017-12-30 18:35:24 +08:00
key := name + ":" + pattern
2017-12-26 10:13:49 +08:00
m[key] = HandlerItem{v.Elem().Type(), name, nil}
}
return s.bindHandlerByMap(m)
}
2017-12-26 10:13:49 +08:00
2017-12-30 18:35:24 +08:00
// 绑定控制器方法pattern支持http method
2017-12-26 10:13:49 +08:00
// pattern的格式形如/user/list, put:/user, delete:/user
// 这种方式绑定的控制器每一次请求都会初始化一个新的控制器对象进行处理,对应不同的请求会话
// 第三个参数methods支持多个方法注册多个方法以英文“,”号分隔
func (s *Server)BindControllerMethod(pattern string, c Controller, methods string) error {
for _, method := range strings.Split(methods, ",") {
item := HandlerItem{reflect.ValueOf(c).Elem().Type(), strings.TrimSpace(method), nil}
if err := s.bindHandlerItem(pattern, item); err != nil {
return err
}
}
return nil
2017-12-26 10:13:49 +08:00
}