createHTTPTask creates a new task with a HTTP target then adds it to a Queue.
(projectID, locationID, queueID, url, message string)
| 27 | |
| 28 | // createHTTPTask creates a new task with a HTTP target then adds it to a Queue. |
| 29 | func createHTTPTask(projectID, locationID, queueID, url, message string) (*taskspb.Task, error) { |
| 30 | |
| 31 | // Create a new Cloud Tasks client instance. |
| 32 | // See https://godoc.org/cloud.google.com/go/cloudtasks/apiv2 |
| 33 | ctx := context.Background() |
| 34 | client, err := cloudtasks.NewClient(ctx) |
| 35 | if err != nil { |
| 36 | return nil, fmt.Errorf("NewClient: %w", err) |
| 37 | } |
| 38 | defer client.Close() |
| 39 | |
| 40 | // Build the Task queue path. |
| 41 | queuePath := fmt.Sprintf("projects/%s/locations/%s/queues/%s", projectID, locationID, queueID) |
| 42 | |
| 43 | // Build the Task payload. |
| 44 | // https://godoc.org/google.golang.org/genproto/googleapis/cloud/tasks/v2#CreateTaskRequest |
| 45 | req := &taskspb.CreateTaskRequest{ |
| 46 | Parent: queuePath, |
| 47 | Task: &taskspb.Task{ |
| 48 | // https://godoc.org/google.golang.org/genproto/googleapis/cloud/tasks/v2#HttpRequest |
| 49 | MessageType: &taskspb.Task_HttpRequest{ |
| 50 | HttpRequest: &taskspb.HttpRequest{ |
| 51 | HttpMethod: taskspb.HttpMethod_POST, |
| 52 | Url: url, |
| 53 | }, |
| 54 | }, |
| 55 | }, |
| 56 | } |
| 57 | |
| 58 | // Add a payload message if one is present. |
| 59 | req.Task.GetHttpRequest().Body = []byte(message) |
| 60 | |
| 61 | createdTask, err := client.CreateTask(ctx, req) |
| 62 | if err != nil { |
| 63 | return nil, fmt.Errorf("cloudtasks.CreateTask: %w", err) |
| 64 | } |
| 65 | |
| 66 | return createdTask, nil |
| 67 | } |
| 68 | |
| 69 | // [END cloud_tasks_create_http_task] |