-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.go
81 lines (69 loc) · 2.29 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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/direktiv/direktiv-apps/pkg/direktivapps"
"google.golang.org/api/idtoken"
"google.golang.org/api/option"
)
// InputContainerDetails ...
type InputContainerDetails struct {
ProjectID string `json:"project-id"`
Region string `json:"region"`
Function string `json:"function"`
ServiceAccountKey string `json:"serviceAccountKey"`
Method string `json:"method"`
Body map[string]interface{} `json:"body"`
}
const code = "com.googleinvoke.error"
func main() {
direktivapps.StartServer(GoogleInvoke)
}
func GoogleInvoke(w http.ResponseWriter, r *http.Request) {
// Read In - Input
obj := new(InputContainerDetails)
_, err := direktivapps.Unmarshal(obj, r)
if err != nil {
direktivapps.RespondWithError(w, code, err.Error())
return
}
// Create Authenticated Client
ctx := context.Background()
cloudFuncURL := fmt.Sprintf("https://%s-%s.cloudfunctions.net/%s", obj.Region, obj.ProjectID, obj.Function)
client, err := idtoken.NewClient(ctx, cloudFuncURL, option.WithCredentialsJSON([]byte(obj.ServiceAccountKey)))
if err != nil {
direktivapps.RespondWithError(w, code, fmt.Sprintf("Failed to create an Authenticated Client: %s", err.Error()))
return
}
// Read In - Cloud Function Payload
var cloudFuncPayload []byte
if obj.Body != nil {
cloudFuncPayload, err = json.Marshal(obj.Body)
if err != nil {
direktivapps.RespondWithError(w, code, err.Error())
return
}
}
// Create and Send Request
resp, err := client.Post(cloudFuncURL, "application/json", bytes.NewReader(cloudFuncPayload))
if err != nil {
direktivapps.RespondWithError(w, code, fmt.Sprintf("GCP Request failed: %v", err))
return
}
defer resp.Body.Close()
bv, err := ioutil.ReadAll(resp.Body)
if err != nil {
direktivapps.RespondWithError(w, code, fmt.Sprintf("GCP Request, could not read response: %v", err))
return
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
// error more than likely
direktivapps.RespondWithError(w, code, fmt.Sprintf("Response Message: %s, Response Code: %v \nResponseBody: %s", resp.Status, resp.StatusCode, bv))
return
}
direktivapps.Respond(w, bv)
}