-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
170 lines (149 loc) · 4.57 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
// Copyright 2020 - Offen Authors <hioffen@posteo.de>
// SPDX-License-Identifier: MPL-2.0
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
const (
githubAssetTypeTarball = "tarball"
versionDevelopment = "development"
versionStable = "stable"
githubRepo = "offen/offen"
storageServer = "storage.offen.dev"
)
var errNotFound = errors.New("not found")
func main() {
r := mux.NewRouter()
r.HandleFunc("/healthz", healthHandler)
r.HandleFunc("/", redirectHandler)
r.HandleFunc("/{param1}", redirectHandler)
r.HandleFunc("/{param1}/{param2}", redirectHandler)
withRecovery := handlers.RecoveryHandler(handlers.PrintRecoveryStack(true))(r)
port := os.Getenv("PORT")
srv := &http.Server{
Addr: fmt.Sprintf("0.0.0.0:%s", port),
Handler: withRecovery,
}
go srv.ListenAndServe()
log.Printf("Server now listening on port %s", port)
quit := make(chan os.Signal)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("Error shutting down server: %v", err)
}
log.Print("Gracefully shut down server")
}
func redirectHandler(w http.ResponseWriter, r *http.Request) {
redirect, err := getRedirect(mux.Vars(r))
if err != nil {
if err == errNotFound {
http.NotFound(w, r)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Location", redirect)
w.WriteHeader(http.StatusFound)
}
func getRedirect(params map[string]string) (string, error) {
if param1, ok := params["param1"]; ok {
switch param1 {
case "deb":
// In case the first URL param is `deb` we assume the user wants to
// download a deb package. No additional parameter will return
// the asset from the latest GitHub release when a second parameter
// looks up the specific URL on S3.
if param2, ok := params["param2"]; ok {
version := param2
version = strings.TrimPrefix(version, "v")
if version == versionDevelopment || version == versionStable {
return "", errNotFound
}
return fmt.Sprintf("https://%s/deb/offen_%s_amd64.deb", storageServer, version), nil
}
return fmt.Sprintf("https://%s/deb/offen_latest_amd64.deb", storageServer), nil
case "crx":
// In case the first URL param is `crx` we assume the user wants to
// download a signed and packaged web extension.
if param2, ok := params["param2"]; ok {
version := param2
version = strings.TrimPrefix(version, "v")
if version == versionDevelopment || version == versionStable {
return "", errNotFound
}
return fmt.Sprintf("https://%s/crx/offen_%s.crx", storageServer, version), nil
}
return fmt.Sprintf("https://%s/crx/offen_latest.crx", storageServer), nil
default:
// The default behavior is to return the tarball containing binaries
return fmt.Sprintf("https://%s/binaries/offen-%s.tar.gz", storageServer, param1), nil
}
}
latest, err := getLatestReleaseInfo()
if err != nil {
return "", fmt.Errorf("error getting latest release: %w", err)
}
asset, assetErr := latest.match(githubAssetTypeTarball)
if assetErr != nil {
return "", errNotFound
}
return asset, nil
}
type releaseInfo struct {
Assets []struct {
BrowserDownloadURL string `json:"browser_download_url"`
} `json:"assets"`
}
func (r *releaseInfo) match(pkgType string) (string, error) {
switch pkgType {
case "deb":
for _, asset := range r.Assets {
if strings.HasSuffix(asset.BrowserDownloadURL, ".deb") {
return asset.BrowserDownloadURL, nil
}
}
case "tarball":
for _, asset := range r.Assets {
if strings.HasSuffix(asset.BrowserDownloadURL, ".tar.gz") {
return asset.BrowserDownloadURL, nil
}
}
default:
return "", fmt.Errorf("unknown package type %s", pkgType)
}
return "", fmt.Errorf("requested release did not contain an asset for %s", pkgType)
}
func getLatestReleaseInfo() (*releaseInfo, error) {
res, err := http.Get(
fmt.Sprintf("https://api.github.com/repos/%s/releases/latest", githubRepo),
)
if err != nil {
return nil, fmt.Errorf("error on HTTP request: %w", err)
}
defer res.Body.Close()
var responseBody releaseInfo
if err := json.NewDecoder(res.Body).Decode(&responseBody); err != nil {
return nil, fmt.Errorf("error decoding response body: %w", err)
}
return &responseBody, nil
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}