I have a channel that receives slices of maps with this code:
func submitRecords(records []map[string]string) {
batch := []map[string]string{}
ch := make(chan []map[string]string)
batchCt := 1
go func() {
for _, v := range records {
batch = append(batch, v)
if len(batch) == 150 {
ch <- batch
batch = nil
}
}
close(ch)
}()
}
The API that I am submitting these records to accepts batches of up to 150. In order to speed this up I would like to spin up 4 go routines to concurrently process the records in the channel. Once the records hit the channel, it doesnt matter what order they get processed.
Currently I made the following update to the above code that runs singularly to process it:
func submitRecords(records []map[string]string) {
batch := []map[string]string{}
ch := make(chan []map[string]string)
batchCt := 1
go func() {
for _, v := range records {
batch = append(batch, v)
if len(batch) == 150 {
ch <- batch
batch = nil
}
}
close(ch)
}()
for b := range ch {
str, _ := json.Marshal(b)
fmt.Printf("Sending batch at line %d\n", (batchCt * 150))
payload := strings.NewReader(string(str))
client := &http.Client{}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
}
login, _ := os.LookupEnv("Login")
password, _ := os.LookupEnv("Password")
req.Header.Add("user_name", login)
req.Header.Add("password", password)
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
batchCt++
}
}
How would I modify this to have 4 go routines pull from the channel and send these requests? Or, is this even possible/have I misunderstood the capabilities of go routines?