server.go 2.0 KB

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