-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
57 lines (45 loc) · 1.3 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
import (
"fmt"
"log"
"net/http"
"os"
"strconv"
"time"
"github.com/uptrace/bunrouter"
)
var start time.Time
func main() {
// Use the log package's default logger
log.SetFlags(log.LstdFlags | log.Lmicroseconds)
// Get the port from the environment variable or default to 8080
port, err := strconv.Atoi(os.Getenv("PORT"))
if err != nil {
port = 8080
}
// Create a new bunrouter
router := bunrouter.New()
// Add a route for the index
router.GET("/", indexHandler)
// Start the server
log.Printf("Listening on :%d\n", port)
// Use http.ListenAndServe() directly instead of logging the return value
if err := http.ListenAndServe(fmt.Sprintf(":%d", port), router); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}
// indexHandler is the handler for the index route
func indexHandler(w http.ResponseWriter, req bunrouter.Request) error {
// Set the content type to JSON
w.Header().Set("Content-Type", "application/json")
// log the request
log.Printf("Received request from %s for %s\n", req.RemoteAddr, req.URL.Path)
// Return a JSON response with the status and uptime, truncated to seconds
return bunrouter.JSON(w,
bunrouter.H{
"status": "alive",
"uptime": time.Since(start).Truncate(time.Second).String(),
"hostname": os.Getenv("HOSTNAME"),
},
)
}