You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
1.5 KiB
64 lines
1.5 KiB
package main
|
|
|
|
import (
|
|
"flag"
|
|
"fmt"
|
|
"net/http"
|
|
{{.importPackages}}
|
|
)
|
|
|
|
var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file")
|
|
|
|
func main() {
|
|
flag.Parse()
|
|
|
|
var c config.Config
|
|
conf.MustLoad(*configFile, &c,conf.UseEnv())
|
|
|
|
server := rest.MustNewServer(c.RestConf,rest.WithNotAllowedHandler(CorsHandler()))
|
|
defer server.Stop()
|
|
server.Use(CorsHandle)
|
|
ctx := svc.NewServiceContext(c)
|
|
handler.RegisterHandlers(server, ctx)
|
|
|
|
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
|
|
server.Start()
|
|
}
|
|
|
|
// setHeader 设置响应头
|
|
func setHeader(w http.ResponseWriter) {
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
w.Header().Set("Access-Control-Allow-Headers", "*")
|
|
w.Header().Set("Access-Control-Allow-Methods", "*")
|
|
w.Header().Set("Access-Control-Expose-Headers", "Content-Length, Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
|
|
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
|
}
|
|
|
|
// CorsHandler 跨域请求处理器
|
|
func CorsHandler() http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
setHeader(w)
|
|
|
|
if r.Method == "OPTIONS" {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
} else {
|
|
w.WriteHeader(http.StatusNotFound)
|
|
}
|
|
})
|
|
}
|
|
|
|
// Handle 跨域请求处理
|
|
func CorsHandle(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
setHeader(w)
|
|
|
|
// 放行所有 OPTIONS 方法
|
|
if r.Method == "OPTIONS" {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
|
|
// 处理请求
|
|
next(w, r)
|
|
}
|
|
}
|
|
|