/
server.go
89 lines (79 loc) · 2.36 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
80
81
82
83
84
85
86
87
88
89
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"github.com/gocraft/web"
)
type Context struct {
Token string
UserInfo map[string]interface{}
CrossyInfo map[string]interface{}
}
func (c *Context) UserRequired(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
var userInfo map[string]interface{}
if req.URL.Path == "/healthcheck" {
next(rw, req)
return
}
auth := req.Header.Get("Authorization")
if !strings.HasPrefix(strings.ToLower(auth), "bearer ") {
rw.WriteHeader(http.StatusUnauthorized)
return
}
token := auth[7:]
client := &http.Client{}
authReq, err := http.NewRequest("GET", "https://meshblu.octoblu.com/v2/whoami", nil)
authReq.Header.Add("Authorization", "Bearer "+token)
resp, err := client.Do(authReq)
if err != nil {
panic(err)
return
}
if err := json.NewDecoder(resp.Body).Decode(&userInfo); err != nil {
panic(err)
}
c.Token = token
c.CrossyInfo = make(map[string]interface{})
c.UserInfo = userInfo
next(rw, req)
}
func (c *Context) GeneratePresigned(rw web.ResponseWriter, req *web.Request) {
rw.Header().Set("Content-Type", "application/json; charset=UTF-8")
rw.WriteHeader(http.StatusOK)
parts := []string{
c.CrossyInfo["username"].(string),
req.PathParams["organization"],
req.PathParams["project"],
req.PathParams["packager"],
req.PathParams["version"],
req.PathParams["platform"],
req.PathParams["arch"],
req.PathParams["file"],
}
path := strings.Join(parts, "/")
presignedURL := GetS3Presigned("contribute-crossy-io", path, 90)
if err := json.NewEncoder(rw).Encode(presignedURL); err != nil {
panic(err)
}
}
func (c *Context) Healthcheck(rw web.ResponseWriter, req *web.Request) {
rw.WriteHeader(http.StatusOK)
fmt.Fprintf(rw, "{\"online\": true}")
}
func main() {
router := web.New(Context{}). // Create your router
Middleware(web.LoggerMiddleware). // Use some included middleware
Middleware(web.ShowErrorsMiddleware). // ...
Middleware((*Context).UserRequired).
// Middleware((*Context).SetHelloCount). // Your own middleware!
Get("/healthcheck", (*Context).Healthcheck).
Post("/api/v1/:organization/:project/:packager/:version/:platform/:arch/:file", (*Context).GeneratePresigned) // Add a route
port := os.Getenv("PORT")
if port == "" {
port = "80"
}
http.ListenAndServe("0.0.0.0:"+port, router) // Start the server!
}