Странное поведение / проблемы с функцией Google Cloud (триггер https)

Я новичок в функции Goggle Cloud, поэтому я не уверен, в чем может быть моя ошибка, поскольку она варьируется от тестов к тестам.

Во-первых, давайте напишем код:

package my_test import ( «encoding/json» «errors» «fmt» «{source_host}/{project}/my_test/models» «net/http» ) // HttpMain prints the JSON encoded «UserId» field in the body // of the request. func HttpMain(w http.ResponseWriter, r *http.Request) { var body models.Body if err := json.NewDecoder(r.Body).Decode(&body); err != nil { _, _ = fmt.Fprintf(w,»%vn», err) } err := Run(w, &body) if err != nil { _, _ = fmt.Fprintf(w,»%vn», err) } _, _ = fmt.Fprintln(w, «Done») } // Run the core part of the function itself. func Run(w http.ResponseWriter, body *models.Body) error { if body == nil { return errors.New(«body parameter is nil») } else if body.UserId == «» { return errors.New(«body.UserId is empty») } else { _, err := fmt.Fprintf(w, «%sn», body.UserId) return err } }

а модель тела выглядит так:

package models type Body struct { UserId string `protobuf:»bytes,1,opt,name=UserId,proto3″ json:»UserId,omitempty»` }

Развертывание (ОК)

Я сделал простой сценарий оболочки, который развертывает мою функцию:

#!/usr/bin/env bash name=»my_test» entryPoint=»HttpMain» yes Y | gcloud functions deploy ${name} —trigger-http —entry-point ${entryPoint} —region europe-west1 —runtime go113 —allow-unauthenticated

Функция развернута, все в порядке.

Странное поведение / проблема …

Что ж, прямо сейчас … у меня есть 3 теста, и каждый из них выдает разные ошибки, и я совершенно не понимаю, почему:

Командная строка Gcloud

Начнем с самого инструмента командной строки. У меня есть такой тест:

#!/usr/bin/env bash name=»my_test» gcloud functions call ${name} —region europe-west1 —data «{«UserId»:»Hey yo buddy»}»

Результат:

macbook-pro-de-emixam23:my_test emixam23$ ./test.sh error: ‘Error: cannot communicate with function.’

Журналы:

D 2020-04-30T09:36:13.702363769Z my_test s1tyqfgxld9u Function execution started my_test s1tyqfgxld9u A 2020-04-30T09:36:13.723Z my_test s1tyqfgxld9u 2020/04/30 09:36:13 project id is required to access Firestore my_test s1tyqfgxld9u D 2020-04-30T09:36:13.813514210Z my_test s1tyqfgxld9u Function execution took 104 ms, finished with status: ‘connection error’ my_test s1tyqfgxld9u

Почтальон

Затем я попробовал от Почтальона:

https://europe-west1-{PROJECT_ID}.cloudfunctions.net/my_test

{ «data»: { «UserId»:»Hey yo buddy» } }

Пожалуйста, проверьте https://stackoverflow.com/a/58210273/6093604 для лучшего понимания поля данных < / сильный>

Результат:

body.UserId is empty Done

Журналы:

D 2020-04-30T09:40:35.019776155Z my_test 9orqtgampnqz Function execution started my_test 9orqtgampnqz D 2020-04-30T09:40:35.246508146Z my_test 9orqtgampnqz Function execution took 227 ms, finished with status code: 200 my_test 9orqtgampnqz

Терминал

Затем я попытался с терминала, используя cURL, но снова другая новая проблема …

macbook-pro-de-emixam23:~ emixam23$ curl -X POST «https://europe-west1-{PROJECT_ID}.cloudfunctions.net/my_test» -H «Content-Type:application/json» —data ‘{«UserId»:»azerty»}’

Результат:

Error: could not handle the request

Журналы:

D 2020-04-30T09:41:51.645842954Z my_test k856kvp2bhun Function execution started my_test k856kvp2bhun A 2020-04-30T09:41:51.698Z my_test k856kvp2bhun 2020/04/30 09:41:51 project id is required to access Firestore my_test k856kvp2bhun D 2020-04-30T09:41:51.712630551Z my_test k856kvp2bhun Function execution took 67 ms, finished with status: ‘connection error’ my_test k856kvp2bhun

Так что, черт возьми, происходит … Как это возможно, что после документа я получаю 3 разные ошибки …

  • error: «Ошибка: невозможно связаться с функцией».
  • Пустой немаршалированный json
  • Ошибка: не удалось обработать запрос

Спасибо за любую помощь ..

Источник: ledsshop.ru

Стиль жизни - Здоровье!