GF框架的WebServer配置管理非常方便,支持多种配置方式以及若干配置方法。

配置对象

配置对象定义: https://godoc.org/github.com/gogf/gf/net/ghttp#ServerConfig

配置管理方法

方法列表: https://godoc.org/github.com/gogf/gf/net/ghttp#Server

简要说明:

  1. 可以通过SetConfigSetConfigWithMap来设置。
  2. 也可以使用Server对象的Set*/Enable*方法进行特定配置的设置。
  3. 主要注意的是,配置项在Server执行Start之后便不能再修改,防止产生并发安全问题。

SetConfigWithMap方法

我们可以使用SetConfigWithMap方法通过Key-Value键值对来设置/修改Server的特定配置,其余的配置使用默认配置即可。其中Key的名称即是ServerConfig这个struct中的属性名称,并且不区分大小写,单词间也支持使用-/_/空格符号连接,具体可参考 类型转换-Struct转换 章节。

简单示例:

s := g.Server()
s.SetConfigWithMap(g.Map{
    "Address":    ":80",
    "ServerRoot": "/var/www/MyServerRoot",
})
s.Run()

其中ServerRoot的键名也可以使用serverRoot, server-root, server_root, server root,其他配置属性以此类推。

一个比较完整的示例:

s := g.Server()
s.SetConfigWithMap(g.Map{
    "Address":          ":80",
    "ServerRoot":       "/var/www/Server",
    "IndexFiles":       g.Slice{"index.html", "main.html"},
    "AccessLogEnabled": true,
    "ErrorLogEnabled":  true,
    "PProfEnabled":     true,
    "LogPath":          "/var/log/ServerLog",
    "SessionIdName":    "MySessionId",
    "SessionPath":      "/tmp/MySessionStoragePath",
    "SessionMaxAge":    24 * time.Hour,
    "DumpRouterMap":    false,
})
s.Run()

配置文件

Server对象也支持通过配置文件进行便捷的配置。支持的配置选项以及配置说明请查看接口文档说明,文档中有详细说明,以下章节不会对配置选项作介绍。

当使用g.Server(单例名称)获取Server单例对象时,将会自动通过默认的配置管理对象获取对应的Server配置。默认情况下会读取server.单例名称配置项,当该配置项不存在时,将会读取server配置项。

支持的配置文件配置项请参考Server配置管理对象属性:https://godoc.org/github.com/gogf/gf/net/ghttp#ServerConfig

示例1,默认配置项

[server]
    Address    = ":80"
    ServerRoot = "/var/www/Server"

随后可以使用g.Server()获取默认的单例对象时自动获取并设置该配置。

示例2,多个配置项

多个Server的配置示例:

[server]
    Address    = ":80"
    ServerRoot = "/var/www/Server"
    [server.server1]
        Address    = ":8080"
        ServerRoot = "/var/www/Server1"
    [server.server2]
        Address    = ":8088"
        ServerRoot = "/var/www/Server2"

我们可以通过单例对象名称获取对应配置的Server单例对象:

// 对应 server.server1 配置项
s1 := g.Server("server1")
// 对应 server.server2 配置项
s2 := g.Server("server2")
// 对应默认配置项 server
s3 := g.Server("none")
// 对应默认配置项 server
s4 := g.Server()

示例3,较完整示例

比如上一个章节的示例,对应的配置文件如下:

[server]
    Address          = ":8199"
    ServerRoot       = "/var/www/Server"
    IndexFiles       = ["index.html", "main.html"]
    AccessLogEnabled = true
    ErrorLogEnabled  = true
    PProfEnabled     = true
    LogPath          = "/var/log/ServerLog"
    SessionIdName    = "MySessionId"
    SessionPath      = "/tmp/MySessionStoragePath"
    SessionMaxAge    = "24h"
    DumpRouterMap    = false

同理,配置属性项的名称也不区分大小写,单词间也支持使用-/_符号连接。也就是说以下配置文件效果和上面的配置文件一致:

[server]
    address          = ":8199"
    serverRoot       = "/var/www/Server"
    indexFiles       = ["index.html", "main.html"]
    accessLogEnabled = true
    errorLogEnabled  = true
    pprofEnabled     = true
    log-path         = "/var/log/ServerLog"
    session_Id_Name  = "MySessionId"
    Session-path     = "/tmp/MySessionStoragePath"
    session_MaxAge   = "24h"
    DumpRouterMap    = false

上传限制

Server对于客户端提交的数据是由大小限制的,主要有两个配置参数控制:

  • MaxHeaderBytes:请求头大小限制,请求头包括客户端提交的Cookie数据,默认设置为10KB
  • ClientMaxBodySize:客户端提交的Body大小限制,同时也影响文件上传大小,默认设置为8MB

由于安全性的考虑,默认的上传限制都不是很高,特别是ClientMaxBodySize的大小限制,在需要文件上传的场景可适当考虑调整,通过配置文件配置即可,例如:

[server]
    MaxHeaderBytes    = "20KB"
    ClientMaxBodySize = "200MB"

这样便修改请求头大小限制为20KB,文件上传大小限制为200MB

配置示例

所有的配置项请参考ServerConfig对象属性: https://godoc.org/github.com/gogf/gf/net/ghttp#ServerConfig

以下为配置示例文件:

[server]
    # 基本配置
    Address             = ":80"                        # 本地监听地址。默认":80"
	HTTPSAddr           = ":443"                       # TLS/HTTPS配置,同时需要配置证书和密钥。默认关闭
	HTTPSCertPath       = ""                           # TLS/HTTPS证书文件本地路径,建议使用绝对路径。默认关闭
	HTTPSKeyPath        = ""                           # TLS/HTTPS密钥文件本地路径,建议使用绝对路径。默认关闭
	ReadTimeout         = "60s"                        # 请求读取超时时间,一般不需要配置。默认为60秒
	WriteTimeout        = "0"                          # 数据返回写入超时时间,一般不需要配置。默认不超时(0)
	IdleTimeout         = "60s"                        # 仅当Keep-Alive开启时有效,请求闲置时间。默认为60秒
	MaxHeaderBytes      = "10240"                      # 请求Header大小限制(Byte)。默认为10KB
	KeepAlive           = true                         # 是否开启Keep-Alive功能。默认true
	ServerAgent         = "GF HTTP Server"             # 服务端Agent信息。默认为"GF HTTP Server"

    # 静态服务配置
	IndexFiles          = ["index.html","index.htm"]   # 自动首页静态文件检索。默认为["index.html", "index.htm"]
	IndexFolder         = false                        # 当访问静态文件目录时,是否展示目录下的文件列表。默认关闭,那么请求将返回403
    ServerRoot          = "/var/www"                   # 静态文件服务的目录根路径,配置时自动开启静态文件服务。默认关闭
	SearchPaths         = ["/home/www","/var/lib/www"] # 提供静态文件服务时额外的文件搜索路径,当根路径找不到时则按照顺序在搜索目录查找。默认关闭
	FileServerEnabled   = false                        # 静态文件服务总开关。默认false

    # Cookie配置
	CookieMaxAge        = "365d"             # Cookie有效期。默认为365天
	CookiePath          = "/"                # Cookie有效路径。默认为"/"表示全站所有路径下有效
	CookieDomain        = ""                 # Cookie有效域名。默认为当前配置Cookie时的域名

	# Sessions配置
	SessionMaxAge       = "24h"              # Session有效期。默认为24小时
	SessionIdName       = "gfsessionid"      # SessionId的键名名称。默认为gfsessionid
	SessionCookieOutput = true               # Session特性开启时,是否将SessionId返回到Cookie中。默认true
	SessionPath         = "/tmp/gsessions"   # Session存储的文件目录路径。默认为当前系统临时目录下的gsessions目录

    # Logging配置
	LogPath             = ""                 # 日志文件存储目录路径,建议使用绝对路径。默认为空,表示关闭
    LogStdout           = true               # 日志是否输出到终端。默认为true
    ErrorStack          = true               # 当Server捕获到异常时是否记录堆栈信息到日志中。默认为true
    ErrorLogEnabled     = true               # 是否记录异常日志信息到日志中。默认为true
    ErrorLogPattern     = "error-{Ymd}.log"  # 异常错误日志文件格式。默认为"error-{Ymd}.log"
    AccessLogEnabled    = false              # 是否记录访问日志。默认为false
    AccessLogPattern    = "access-{Ymd}.log" # 访问日志文件格式。默认为"access-{Ymd}.log"

    # PProf配置
	PProfEnabled        = false              # 是否开启PProf性能调试特性。默认为false
	PProfPattern        = ""                 # 开启PProf时有效,表示PProf特性的页面访问路径,对当前Server绑定的所有域名有效。

    # 其他配置
	ClientMaxBodySize   = 810241024          # 客户端最大Body上传限制大小,影响文件上传大小(Byte)。默认为8*1024*1024=8MB
	FormParsingMemory   = 1048576            # 解析表单时的缓冲区大小(Byte),一般不需要配置。默认为1024*1024=1MB
	NameToUriType       = 0                  # 路由注册中使用对象注册时的路由生成规则。默认为0
	RouteOverWrite      = false              # 当遇到重复路由注册时是否强制覆盖。默认为false,重复路由存在时将会在启动时报错退出
	DumpRouterMap       = true               # 是否在Server启动时打印所有的路由列表。默认为true
	Graceful            = false              # 是否开启平滑重启特性,开启时将会在本地增加10000的本地TCP端口用于进程间通信。默认false
Content Menu

  • No labels

2 Comments


  1. NameToUriType       = 0                  # 路由注册中使用对象注册时的路由生成规则。默认为0

    是否还有其他值,看gf-demos项目里用的是2. 这些取值能否详细说明一下


    1. // nameToUri converts the given name to the URL format using the following rules:
      // Rule 0: Convert all method names to lowercase, add char '-' between words.
      // Rule 1: Do not convert the method name, construct the URI with the original method name.
      // Rule 2: Convert all method names to lowercase, no connecting symbols between words.
      // Rule 3: Use camel case naming.