gracefulhandler.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package handler
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "time"
  8. "github.com/tal-tech/go-zero/core/executors"
  9. "github.com/tal-tech/go-zero/core/logx"
  10. "github.com/tal-tech/go-zero/example/graceful/etcd/api/svc"
  11. "github.com/tal-tech/go-zero/example/graceful/etcd/api/types"
  12. "github.com/tal-tech/go-zero/example/graceful/etcd/rpc/graceful"
  13. "github.com/tal-tech/go-zero/rest/httpx"
  14. )
  15. func gracefulHandler(ctx *svc.ServiceContext) http.HandlerFunc {
  16. logger := executors.NewLessExecutor(time.Second)
  17. return func(w http.ResponseWriter, r *http.Request) {
  18. host, err := os.Hostname()
  19. if err != nil {
  20. http.Error(w, http.StatusText(http.StatusNotImplemented), http.StatusNotImplemented)
  21. return
  22. }
  23. conn := ctx.Client.Conn()
  24. client := graceful.NewGraceServiceClient(conn)
  25. rp, err := client.Grace(context.Background(), &graceful.Request{From: host})
  26. if err != nil {
  27. logx.Error(err)
  28. http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
  29. return
  30. }
  31. var resp types.Response
  32. resp.Host = rp.Host
  33. logger.DoOrDiscard(func() {
  34. fmt.Printf("%s from host: %s\n", time.Now().Format("15:04:05"), rp.Host)
  35. })
  36. httpx.OkJson(w, resp)
  37. }
  38. }