main.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "github.com/longjoy/micro-go-course/section10/user/dao"
  7. "github.com/longjoy/micro-go-course/section10/user/endpoint"
  8. "github.com/longjoy/micro-go-course/section10/user/redis"
  9. "github.com/longjoy/micro-go-course/section10/user/service"
  10. "github.com/longjoy/micro-go-course/section10/user/transport"
  11. "log"
  12. "net/http"
  13. "os"
  14. "os/signal"
  15. "strconv"
  16. "syscall"
  17. "time"
  18. )
  19. func main() {
  20. var (
  21. // 服务地址和服务名
  22. servicePort = flag.Int("service.port", 10086, "service port")
  23. //waitTime = flag.Int("wait.time", 10, "wait time")
  24. )
  25. flag.Parse()
  26. time.Sleep(10 * time.Second) // 延时启动,等待 MySQL 和 Redis 准备好
  27. ctx := context.Background()
  28. errChan := make(chan error)
  29. err := dao.InitMysql("127.0.0.1", "3306", "root", "123456", "user")
  30. if err != nil{
  31. log.Fatal(err)
  32. }
  33. err = redis.InitRedis("127.0.0.1","6379", "" )
  34. if err != nil{
  35. log.Fatal(err)
  36. }
  37. userService := service.MakeUserServiceImpl(&dao.UserDAOImpl{})
  38. userEndpoints := &endpoint.UserEndpoints{
  39. endpoint.MakeRegisterEndpoint(userService),
  40. endpoint.MakeLoginEndpoint(userService),
  41. }
  42. r := transport.MakeHttpHandler(ctx, userEndpoints)
  43. go func() {
  44. errChan <- http.ListenAndServe(":" + strconv.Itoa(*servicePort), r)
  45. }()
  46. go func() {
  47. // 监控系统信号,等待 ctrl + c 系统信号通知服务关闭
  48. c := make(chan os.Signal, 1)
  49. signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
  50. errChan <- fmt.Errorf("%s", <-c)
  51. }()
  52. error := <-errChan
  53. log.Println(error)
  54. }