gracefulhandler.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package handler
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "time"
  8. "zero/core/executors"
  9. "zero/core/logx"
  10. "zero/example/graceful/dns/api/svc"
  11. "zero/example/graceful/dns/api/types"
  12. "zero/example/graceful/dns/rpc/graceful"
  13. "zero/ngin/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. var resp types.Response
  19. conn, ok := ctx.Client.Next()
  20. if !ok {
  21. http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  22. return
  23. }
  24. host, err := os.Hostname()
  25. if err != nil {
  26. http.Error(w, http.StatusText(http.StatusNotImplemented), http.StatusNotImplemented)
  27. return
  28. }
  29. client := graceful.NewGraceServiceClient(conn)
  30. rp, err := client.Grace(context.Background(), &graceful.Request{From: host})
  31. if err != nil {
  32. logx.Error(err)
  33. http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway)
  34. return
  35. }
  36. resp.Host = rp.Host
  37. logger.DoOrDiscard(func() {
  38. fmt.Printf("%s from host: %s\n", time.Now().Format("15:04:05"), rp.Host)
  39. })
  40. httpx.OkJson(w, resp)
  41. }
  42. }