generated from koddr/template-go
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
79 lines (67 loc) · 2.59 KB
/
server.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"fmt"
"image/png"
"log/slog"
"net/http"
"time"
)
// runServer runs a new HTTP server with the loaded environment variables.
func runServer() error {
// Validate environment variables and create a new application.
app, err := validateEnvVariables()
if err != nil {
return err
}
// Fetch URLs of the avatar images of stargazers and contributors.
images, err := app.fetchImages()
if err != nil {
return err
}
// Log the number of avatar images collected.
slog.Info(
"successfully collected avatar images",
"stargazers", len(images.Stargazers), "contributors", len(images.Contributors),
)
// Call prepareFinalImage with the required parameters for stargazers.
stargazersFinalImage, err := app.prepareFinalImage(images.Stargazers)
if err != nil {
return err
}
// Call prepareFinalImage with the required parameters for contributors.
contributorsFinalImage, err := app.prepareFinalImage(images.Contributors)
if err != nil {
return err
}
// Create endpoints URLs for stargazers and contributors.
stargazersEndpoint := fmt.Sprintf("/github/%s/%s/stargazers.png", app.Repository.Owner, app.Repository.Name)
contributorsEndpoint := fmt.Sprintf("/github/%s/%s/contributors.png", app.Repository.Owner, app.Repository.Name)
// Serve the final image for stargazers using an HTTP server.
http.HandleFunc(stargazersEndpoint, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/png")
if err := png.Encode(w, stargazersFinalImage); err != nil {
slog.Error("encode to image/png", "details", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
// Serve the final image for contributors using an HTTP server.
http.HandleFunc(contributorsEndpoint, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/png")
if err := png.Encode(w, contributorsFinalImage); err != nil {
slog.Error("encode to image/png", "details", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
// Start a goroutine to continuously update the final images.
go app.updateFinalImage(stargazersFinalImage, contributorsFinalImage)
// Create a new server instance with options from environment variables.
// For more information, see https://blog.cloudflare.com/the-complete-guide-to-golang-net-http-timeouts/
server := &http.Server{
Addr: fmt.Sprintf(":%d", app.Server.Port),
ReadTimeout: time.Duration(app.Server.ReadTimeout) * time.Second,
WriteTimeout: time.Duration(app.Server.WriteTimeout) * time.Second,
}
return server.ListenAndServe()
}