@@ -148,3 +148,55 @@ func main() {
148
148
server.Start ()
149
149
}
150
150
```
151
+
152
+ ### 自定义复杂的跨域设置示例
153
+
154
+ 示例代码如下:
155
+
156
+ ``` go
157
+ package main
158
+
159
+ import (
160
+ " flag"
161
+ " fmt"
162
+ " net/http"
163
+ " os"
164
+
165
+ " github.com/zeromicro/go-zero/core/logx"
166
+ " github.com/zeromicro/go-zero/core/conf"
167
+ " github.com/zeromicro/go-zero/rest"
168
+ " github.com/zeromicro/go-zero/rest/httpx"
169
+ )
170
+
171
+ var configFile = flag.String (" f" , " etc/core-api-dev.yaml" , " the config file" )
172
+
173
+ func main () {
174
+ flag.Parse ()
175
+
176
+ var c config.Config
177
+ conf.MustLoad (*configFile, &c)
178
+
179
+ # 需要通过的域名,这里可以写多个域名 或者可以写 * 全部通过
180
+ domains := []string {" *" ," http://127.0.0.1" , " https://go-zero.dev" , " http://localhost" }
181
+ server := rest.MustNewServer (
182
+ c.RestConf ,
183
+ rest.WithCors (domains...),
184
+ rest.WithCustomCors (func (header http.Header ) {
185
+ # 这里写允许通过的header key 不区分大小写
186
+ header.Add (" Access-Control-Allow-Headers" , " Content-Type,AccessToken,X-CSRF-Token,Authorization,Token,X-Token,X-User-Id,OS,Platform, Version" )
187
+ header.Set (" Access-Control-Allow-Methods" , " GET,POST,PUT,DELETE,OPTIONS,PATCH" )
188
+ header.Set (" Access-Control-Expose-Headers" , " Content-Length, Content-Type" )
189
+ }, nil , " *" ),
190
+ )
191
+
192
+ defer server.Stop ()
193
+
194
+ ctx := svc.NewServiceContext (c)
195
+ handler.RegisterHandlers (server, ctx)
196
+
197
+
198
+ fmt.Printf (" Starting admin_user-api server at %s :%d ...\n " , c.Host , c.Port )
199
+ server.Start ()
200
+ }
201
+
202
+ ```
0 commit comments