| giolekva | 60e87d3 | 2020-05-01 23:07:42 +0400 | [diff] [blame^] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "flag" |
| 7 | "fmt" |
| 8 | "io/ioutil" |
| 9 | "log" |
| 10 | "net/http" |
| 11 | |
| 12 | "github.com/golang/glog" |
| 13 | "github.com/itaysk/regogo" |
| 14 | ) |
| 15 | |
| 16 | var port = flag.Int("port", 123, "Port to listen on.") |
| 17 | var apiAddr = flag.String("api_addr", "", "PCloud GraphQL API server address.") |
| 18 | |
| 19 | var jsonContentType = "application/json" |
| 20 | |
| 21 | var addImgTmpl = ` |
| 22 | mutation { |
| 23 | addImage(input: [%s]) { |
| 24 | image { |
| 25 | id |
| 26 | } |
| 27 | } |
| 28 | }` |
| 29 | |
| 30 | type image struct { |
| 31 | ObjectPath string |
| 32 | } |
| 33 | |
| 34 | type query struct { |
| 35 | Query string |
| 36 | } |
| 37 | |
| 38 | func minioHandler(w http.ResponseWriter, r *http.Request) { |
| 39 | body, err := ioutil.ReadAll(r.Body) |
| 40 | if err != nil { |
| 41 | glog.Error(err) |
| 42 | http.Error(w, "Could not read HTTP request body", http.StatusInternalServerError) |
| 43 | return |
| 44 | } |
| 45 | if len(body) == 0 { |
| 46 | // Just a health check from Minio |
| 47 | return |
| 48 | } |
| 49 | bodyStr := string(body) |
| 50 | glog.Infof("Received event from Minio: %s", bodyStr) |
| 51 | key, err := regogo.Get(bodyStr, "input.Key") |
| 52 | if err != nil { |
| 53 | glog.Error(err) |
| 54 | http.Error(w, "Could not find object key", http.StatusBadRequest) |
| 55 | return |
| 56 | } |
| 57 | img := image{key.String()} |
| 58 | imgJson, err := json.Marshal(img) |
| 59 | if err != nil { |
| 60 | panic(err) |
| 61 | } |
| 62 | q := query{fmt.Sprintf(addImgTmpl, imgJson)} |
| 63 | glog.Info(q) |
| 64 | queryJson, err := json.Marshal(q) |
| 65 | if err != nil { |
| 66 | panic(err) |
| 67 | } |
| 68 | resp, err := http.Post( |
| 69 | *apiAddr, |
| 70 | jsonContentType, |
| 71 | bytes.NewReader(queryJson)) |
| 72 | if err != nil { |
| 73 | glog.Error(err) |
| 74 | http.Error(w, "Query failed", http.StatusInternalServerError) |
| 75 | return |
| 76 | } |
| 77 | respBody, err := ioutil.ReadAll(resp.Body) |
| 78 | if err != nil { |
| 79 | panic(err) |
| 80 | } |
| 81 | glog.Info(string(respBody)) |
| 82 | } |
| 83 | |
| 84 | func main() { |
| 85 | flag.Parse() |
| 86 | |
| 87 | http.HandleFunc("/minio_webhook", minioHandler) |
| 88 | log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil)) |
| 89 | } |