---
title: "服务配置-配置方法"
url: "https://goframe.org/docs/web/server-config-funcs"
markdown_url: "https://goframe.org/docs/web/server-config-funcs.md"
locale: "zh-Hans"
version: "2.10.x(Latest)"
section: "WEB 服务开发"
category: "WEB 服务开发 / 服务配置"
published: "2024-10-21"
updated: "2024-11-11"
description: "在GoFrame框架中通过SetConfig和SetConfigWithMap方法对服务器进行配置，包括配置对象ServerConfig的定义及使用Server对象进行特定配置。需要注意的是，配置项在Server执行Start后便不能再修改，以保证并发安全。"
keywords: ["GoFrame", "GoFrame框架", "服务配置", "SetConfig", "SetConfigWithMap", "ServerConfig", "配置方法", "ghttp库", "服务器", "配置对象"]
---

# 服务配置-配置方法

## 配置对象

配置对象定义： [https://pkg.go.dev/github.com/gogf/gf/v2/net/ghttp#ServerConfig](https://pkg.go.dev/github.com/gogf/gf/v2/net/ghttp#ServerConfig)

## 配置方法

方法列表： [https://pkg.go.dev/github.com/gogf/gf/v2/net/ghttp#Server](https://pkg.go.dev/github.com/gogf/gf/v2/net/ghttp#Server)

简要说明：

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

### `SetConfigWithMap` 方法

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

简单示例：

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

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

一个比较完整的示例：

```go
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()
```
