server.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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-ip2location/internal/server/web"
  13. "github.com/vladimirok5959/golang-utils/utils/http/apiserv"
  14. "github.com/vladimirok5959/golang-utils/utils/http/helpers"
  15. )
  16. func NewMux(ctx context.Context, shutdown context.CancelFunc, client *client.Client) *apiserv.ServeMux {
  17. mux := apiserv.NewServeMux()
  18. handler := base.Handler{
  19. Client: client,
  20. Shutdown: shutdown,
  21. }
  22. // Pages
  23. mux.Get("/", page_index.Handler{Handler: handler})
  24. // API
  25. mux.Get("/api/v1/app/health", v1_app_health.Handler{Handler: handler})
  26. mux.Get("/api/v1/app/status", helpers.HandleAppStatus())
  27. mux.Get("/api/v1/ip2location/{s}", v1_ip2location.Handler{Handler: handler})
  28. // Assets
  29. mux.Get("/styles.css", helpers.HandleTextCss(web.StylesCss))
  30. return mux
  31. }
  32. func New(ctx context.Context, shutdown context.CancelFunc, client *client.Client) (*http.Server, error) {
  33. mux := NewMux(ctx, shutdown, client)
  34. srv := &http.Server{
  35. Addr: consts.Config.Host + ":" + consts.Config.Port,
  36. Handler: mux,
  37. }
  38. go func() {
  39. fmt.Printf("Web server: http://%s:%s/\n", consts.Config.Host, consts.Config.Port)
  40. if err := srv.ListenAndServe(); err != nil {
  41. if err != http.ErrServerClosed {
  42. fmt.Printf("Web server startup error: %s\n", err.Error())
  43. shutdown()
  44. return
  45. }
  46. }
  47. }()
  48. return srv, nil
  49. }