|
| 1 | +package ciscofonserver |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "net/http" |
| 8 | + "strings" |
| 9 | + |
| 10 | + "github.com/gofiber/fiber/v2" |
| 11 | + "github.com/gofiber/template/html/v2" |
| 12 | +) |
| 13 | + |
| 14 | +func (s *CiscoFonServer) startHTTPServer() { |
| 15 | + engine := html.NewFileSystem(http.FS(templatesFS), ".html") |
| 16 | + app := fiber.New(fiber.Config{ |
| 17 | + Views: engine, |
| 18 | + |
| 19 | + ErrorHandler: func(c *fiber.Ctx, err error) error { |
| 20 | + // Status code defaults to 500 |
| 21 | + code := fiber.StatusInternalServerError |
| 22 | + |
| 23 | + // Retrieve the custom status code if it's a *fiber.Error |
| 24 | + var e *fiber.Error |
| 25 | + if errors.As(err, &e) { |
| 26 | + code = e.Code |
| 27 | + } |
| 28 | + s.logRequest("HTTP", c.Method(), c.Path(), fmt.Sprintf("%d", code), c.IP()) |
| 29 | + |
| 30 | + c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8) |
| 31 | + |
| 32 | + // Return from handler |
| 33 | + return c.Status(code).SendString(err.Error()) |
| 34 | + }, |
| 35 | + }) |
| 36 | + |
| 37 | + app.Use(func(c *fiber.Ctx) error { |
| 38 | + err := c.Next() |
| 39 | + if !strings.HasPrefix(c.Path(), "/dashboard") && err == nil { |
| 40 | + s.logRequest("HTTP", c.Method(), c.Path(), "200", c.IP()) |
| 41 | + } |
| 42 | + return err |
| 43 | + }) |
| 44 | + |
| 45 | + app.All("*.xml", func(c *fiber.Ctx) error { |
| 46 | + c.Set(fiber.HeaderContentType, "text/xml") |
| 47 | + return c.Next() |
| 48 | + }) |
| 49 | + |
| 50 | + app.Static("/", s.config.String("http.dir")) |
| 51 | + |
| 52 | + s.registerDashboardRoutes(app) |
| 53 | + |
| 54 | + log.Println("Starting HTTP server on", s.config.String("http.port")) |
| 55 | + err := app.Listen(":" + s.config.String("http.port")) |
| 56 | + if err != nil { |
| 57 | + log.Fatalf("HTTP server error: %v", err) |
| 58 | + } |
| 59 | +} |
0 commit comments