Ai
1 Star 0 Fork 0

mosache/go-zero

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
main.go 1.38 KB
一键复制 编辑 原始数据 按行查看 历史
kevwan 提交于 2020-10-21 14:10 +08:00 . support cors in rest server
package main
import (
"flag"
"net/http"
"github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/service"
"github.com/tal-tech/go-zero/rest"
"github.com/tal-tech/go-zero/rest/httpx"
)
var (
port = flag.Int("port", 3333, "the port to listen")
timeout = flag.Int64("timeout", 0, "timeout of milliseconds")
)
type Request struct {
User string `form:"user,options=a|b"`
}
func first(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("X-Middleware", "first")
next(w, r)
}
}
func second(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("X-Middleware", "second")
next(w, r)
}
}
func handle(w http.ResponseWriter, r *http.Request) {
var req Request
err := httpx.Parse(r, &req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
httpx.OkJson(w, "helllo, "+req.User)
}
func main() {
flag.Parse()
engine := rest.MustNewServer(rest.RestConf{
ServiceConf: service.ServiceConf{
Log: logx.LogConf{
Mode: "console",
},
},
Port: *port,
Timeout: *timeout,
MaxConns: 500,
}, rest.WithNotAllowedHandler(rest.CorsHandler()))
defer engine.Stop()
engine.Use(first)
engine.Use(second)
engine.AddRoute(rest.Route{
Method: http.MethodGet,
Path: "/",
Handler: handle,
})
engine.Start()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/mosache/go-zero.git
git@gitee.com:mosache/go-zero.git
mosache
go-zero
go-zero
dfb45c801a6c

搜索帮助