d76241a06f9ecb349c23b4c966b74c36c68c9d91.svn-base 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "github.com/google/uuid"
  7. "github.com/longjoy/micro-go-course/section28/comment/endpoint"
  8. "github.com/longjoy/micro-go-course/section28/comment/pkg/discovery"
  9. "github.com/longjoy/micro-go-course/section28/comment/service"
  10. "github.com/longjoy/micro-go-course/section28/comment/transport"
  11. "log"
  12. "net/http"
  13. "os"
  14. "os/signal"
  15. "strconv"
  16. "syscall"
  17. )
  18. func main() {
  19. consulAddr := flag.String("consul.addr", "localhost", "consul address")
  20. consulPort := flag.Int("consul.port", 8500, "consul port")
  21. servicePort := flag.Int("service.port", 13312, "service port")
  22. serviceName := flag.String("service.name", "comment", "service name")
  23. serviceAddr := flag.String("service.addr", "127.0.0.1", "service addr")
  24. flag.Parse()
  25. client := discovery.NewDiscoveryClient(*consulAddr, *consulPort)
  26. instanceId := *serviceName + "-" + uuid.New().String()
  27. err := client.Register(context.Background(), *serviceName, instanceId, "/health", *serviceAddr, *servicePort, nil, nil)
  28. errChan := make(chan error)
  29. srv := service.NewGoodsServiceImpl()
  30. endpoints := endpoint.CommentsEndpoints{
  31. CommentsListEndpoint: endpoint.MakeCommentsListEndpoint(srv),
  32. HealthCheckEndpoint: endpoint.MakeHealthCheckEndpoint(srv),
  33. }
  34. handler := transport.MakeHttpHandler(context.Background(), &endpoints)
  35. go func() {
  36. errChan <- http.ListenAndServe(":"+strconv.Itoa(*servicePort), handler)
  37. }()
  38. go func() {
  39. // 监控系统信号,等待 ctrl + c 系统信号通知服务关闭
  40. c := make(chan os.Signal, 1)
  41. signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
  42. errChan <- fmt.Errorf("%s", <-c)
  43. }()
  44. err = <-errChan
  45. log.Printf("listen err : %s", err)
  46. client.Deregister(context.Background(), instanceId)
  47. }