go-zero/example/http/post/main.go

66 lines
1.2 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package main
import (
"flag"
"fmt"
"net/http"
2020-08-08 16:40:10 +08:00
"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"
2020-07-26 17:09:05 +08:00
)
var (
port = flag.Int("port", 3333, "the port to listen")
timeout = flag.Int64("timeout", 0, "timeout of milliseconds")
)
type Request struct {
User string `json:"user"`
}
func handleGet(w http.ResponseWriter, r *http.Request) {
}
func handlePost(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, fmt.Sprintf("Content-Length: %d, UserLen: %d", r.ContentLength, len(req.User)))
}
func main() {
flag.Parse()
2020-07-31 11:45:16 +08:00
engine := rest.MustNewServer(rest.RestConf{
2020-07-26 17:09:05 +08:00
ServiceConf: service.ServiceConf{
Log: logx.LogConf{
Mode: "console",
},
},
Port: *port,
Timeout: *timeout,
MaxConns: 500,
MaxBytes: 50,
CpuThreshold: 500,
})
defer engine.Stop()
2020-07-31 11:14:48 +08:00
engine.AddRoute(rest.Route{
2020-07-26 17:09:05 +08:00
Method: http.MethodGet,
Path: "/",
Handler: handleGet,
})
2020-07-31 11:14:48 +08:00
engine.AddRoute(rest.Route{
2020-07-26 17:09:05 +08:00
Method: http.MethodPost,
Path: "/",
Handler: handlePost,
})
engine.Start()
}