-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmirror_serve_http.go
100 lines (92 loc) · 2.39 KB
/
mirror_serve_http.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
// Copyright (c) The OpenTofu Authors
// SPDX-License-Identifier: MPL-2.0
package tofudl
import (
"context"
"encoding/json"
"net/http"
"strings"
)
func (m *mirror) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
ctx := context.Background()
if request.RequestURI == "/api.json" {
m.serveAPI(ctx, writer)
return
}
m.serveAsset(ctx, writer, request)
}
func (m *mirror) serveAPI(ctx context.Context, writer http.ResponseWriter) {
versionList, err := m.ListVersions(ctx)
if err != nil {
m.badGateway(writer)
return
}
response := APIResponse{
Versions: versionList,
}
encoded, err := json.Marshal(response)
if err != nil {
m.badGateway(writer)
return
}
writer.WriteHeader(http.StatusOK)
writer.Header().Set("Content-Type", "application/json")
_, _ = writer.Write(encoded)
}
func (m *mirror) serveAsset(ctx context.Context, writer http.ResponseWriter, request *http.Request) {
if !strings.HasPrefix(request.RequestURI, "/") {
m.badRequest(writer)
return
}
parts := strings.Split(request.RequestURI, "/")
if len(parts) != 3 {
m.notFound(writer)
return
}
version := Version(strings.TrimPrefix(parts[1], "v"))
if err := version.Validate(); err != nil {
m.notFound(writer)
return
}
versions, err := m.ListVersions(ctx)
if err != nil {
m.badGateway(writer)
return
}
var foundVersion *VersionWithArtifacts
for _, ver := range versions {
ver := ver
if ver.ID == version {
foundVersion = &ver
break
}
}
if foundVersion == nil {
m.notFound(writer)
return
}
// TODO implement stream reading
contents, err := m.DownloadArtifact(ctx, *foundVersion, parts[2])
if err != nil {
m.badGateway(writer)
return
}
writer.WriteHeader(http.StatusOK)
writer.Header().Set("Content-Type", "application/octet-stream")
_, _ = writer.Write(contents)
}
func (m *mirror) badRequest(writer http.ResponseWriter) {
writer.WriteHeader(http.StatusBadRequest)
writer.Header().Set("Content-Type", "text/html")
_, _ = writer.Write([]byte("<h1>Bad request</h1>"))
}
func (m *mirror) badGateway(writer http.ResponseWriter) {
writer.WriteHeader(http.StatusBadGateway)
writer.Header().Set("Content-Type", "text/html")
_, _ = writer.Write([]byte("<h1>Bad gateway</h1>"))
}
func (m *mirror) notFound(writer http.ResponseWriter) {
writer.WriteHeader(http.StatusNotFound)
writer.Header().Set("Content-Type", "text/html")
_, _ = writer.Write([]byte("<h1>Bad gateway</h1>"))
}