| giolekva | 07f6be9 | 2020-04-16 21:09:30 +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 | |
| 13 | var port = flag.Int("port", 123, "Port to listen on.") |
| 14 | var graphql_address = flag.String("graphql_address", "", "GraphQL server address.") |
| 15 | |
| 16 | func minio_webhook_handler(w http.ResponseWriter, r *http.Request) { |
| 17 | body, err := ioutil.ReadAll(r.Body) |
| 18 | if len(body) == 0 { |
| 19 | return |
| 20 | } |
| 21 | log.Print(string(body)) |
| 22 | if err != nil { |
| 23 | log.Print("-----") |
| 24 | log.Print(err) |
| 25 | http.Error(w, "Could not read HTTP request body", http.StatusInternalServerError) |
| 26 | return |
| 27 | } |
| 28 | event := make(map[string]interface{}) |
| 29 | err = json.Unmarshal(body, &event) |
| 30 | if err != nil { |
| 31 | log.Print("++++++") |
| 32 | log.Print(err) |
| 33 | http.Error(w, "Could not parse Event JSON object", http.StatusBadRequest) |
| 34 | return |
| 35 | } |
| 36 | buf := []byte("{ \"query\": \"mutation { addImage(input: [{ objectPath: \\\"" + event["Key"].(string) + "\\\"}]) { image { id } }} \" }") |
| 37 | log.Print(string(buf)) |
| 38 | resp, err := http.Post(*graphql_address, "application/json", bytes.NewReader(buf)) |
| 39 | if err != nil { |
| 40 | log.Print("#######") |
| 41 | log.Print(err) |
| 42 | http.Error(w, "Could not post to GraphQL", http.StatusInternalServerError) |
| 43 | return |
| 44 | } |
| 45 | body, err = ioutil.ReadAll(resp.Body) |
| 46 | if err != nil { |
| 47 | log.Print("@@@@@@") |
| 48 | log.Print(err) |
| 49 | http.Error(w, "Could not parse GraphQL response", http.StatusInternalServerError) |
| 50 | return |
| 51 | } |
| 52 | log.Print(string(body)) |
| 53 | } |
| 54 | |
| 55 | func main() { |
| 56 | flag.Parse() |
| 57 | http.HandleFunc("/minio_webhook", minio_webhook_handler) |
| 58 | log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil)) |
| 59 | } |