server.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package server
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "github.com/vladimirok5959/golang-ip2location/internal/client"
  7. "github.com/vladimirok5959/golang-ip2location/internal/consts"
  8. "github.com/vladimirok5959/golang-ip2location/internal/server/handler/api/v1/v1_app_health"
  9. "github.com/vladimirok5959/golang-ip2location/internal/server/handler/api/v1/v1_ip2location"
  10. "github.com/vladimirok5959/golang-ip2location/internal/server/handler/base"
  11. "github.com/vladimirok5959/golang-ip2location/internal/server/handler/page/page_index"
  12. "github.com/vladimirok5959/golang-utils/utils/http/apiserv"
  13. "github.com/vladimirok5959/golang-utils/utils/http/helpers"
  14. )
  15. func NewMux(ctx context.Context, shutdown context.CancelFunc, client *client.Client) *apiserv.ServeMux {
  16. mux := apiserv.NewServeMux()
  17. handler := base.Handler{
  18. Client: client,
  19. Shutdown: shutdown,
  20. }
  21. // Pages
  22. mux.Get("/", page_index.Handler{Handler: handler})
  23. // API
  24. mux.Get("/api/v1/app/health", v1_app_health.Handler{Handler: handler})
  25. mux.Get("/api/v1/app/status", helpers.HandleAppStatus())
  26. mux.Get("/api/v1/ip2location/{s}", v1_ip2location.Handler{Handler: handler})
  27. return mux
  28. }
  29. func New(ctx context.Context, shutdown context.CancelFunc, client *client.Client) (*http.Server, error) {
  30. mux := NewMux(ctx, shutdown, client)
  31. srv := &http.Server{
  32. Addr: consts.Config.Host + ":" + consts.Config.Port,
  33. Handler: mux,
  34. }
  35. go func() {
  36. fmt.Printf("Web server: http://%s:%s/\n", consts.Config.Host, consts.Config.Port)
  37. if err := srv.ListenAndServe(); err != nil {
  38. if err != http.ErrServerClosed {
  39. fmt.Printf("Web server startup error: %s\n", err.Error())
  40. shutdown()
  41. return
  42. }
  43. }
  44. }()
  45. return srv, nil
  46. }