You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/example/http/post/main.go

66 lines
1.1 KiB
Go

4 years ago
package main
import (
"flag"
"fmt"
"net/http"
"zero/core/logx"
"zero/core/service"
"zero/ngin"
4 years ago
"zero/ngin/httpx"
4 years ago
)
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()
engine := ngin.MustNewEngine(ngin.NgConf{
ServiceConf: service.ServiceConf{
Log: logx.LogConf{
Mode: "console",
},
},
Port: *port,
Timeout: *timeout,
MaxConns: 500,
MaxBytes: 50,
CpuThreshold: 500,
})
defer engine.Stop()
engine.AddRoute(ngin.Route{
Method: http.MethodGet,
Path: "/",
Handler: handleGet,
})
engine.AddRoute(ngin.Route{
Method: http.MethodPost,
Path: "/",
Handler: handlePost,
})
engine.Start()
}