Repository: microsoft/kiota (csharp)

Issue:
Go: Broken Generated Code when Body is an Array of Scalar Values
Hey team :wave: 

Hope this is the right place to open Golang generation issues, today I faced a weird issue that I will try to describe below.

It seems that the generator produces a broken Golang code when trying to parse a `body` made by an array of scalars.

```yaml
paths:
  /posts:
    post:
      description: 'Create post'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: array
              items:
                format: int32
                type: integer
      responses:
        '201':
          description: Created
          content:
            application/json:
              schema:
                type: array
                items:
                  format: int32
                  type: integer
```

The generated `ToPostRequestInformation` is something like:

```go
// ToPostRequestInformation create post
// returns a *RequestInformation when successful
func (m *PostsRequestBuilder) ToPostRequestInformation(ctx context.Context, body []int32, requestConfiguration *PostsRequestBuilderPostRequestConfiguration)(*i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestInformation, error) {
    requestInfo := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.NewRequestInformationWithMethodAndUrlTemplateAndPathParameters(i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.POST, "{+baseurl}/posts", m.BaseRequestBuilder.PathParameters)
    if requestConfiguration != nil {
        requestInfo.Headers.AddAll(requestConfiguration.Headers)
        requestInfo.AddRequestOptions(requestConfiguration.Options)
    }
    requestInfo.Headers.TryAdd("Accept", "application/json")
    requestInfo.SetContentFromScalarCollection(ctx, m.BaseRequestBuilder.RequestAdapter, "application/json", body)
    return requestInfo, nil
}
```

The issue is that `requestInfo.SetContentFromScalarCollection(ctx, m.BaseRequestBuilder.RequestAdapter, "application/json", body)` cannot receive `body` (which is a `[]int32`) as it is expecting a `[]interface{}` type which is not allowed [1].

![image](https://github.com/microsoft/kiota/assets/26715795/af6d9095-3f13-4d44-bae7-64a405510890)

Maybe I missed something or I am doing something wrong (in that case, please let me know) but I think that the openapi is a valid one, therefore I am expecting a valid generated code.

## Version

```bash
kiota --version                                                                                                                                                                              [17:54:51]
1.12.0+1735a2ff916ebec661974d9560f1dd00d3dc349b
```

```bash
go version                                                                                                                                                                                   [17:55:22]
go version go1.21.8 linux/amd64
```

## How to reproduce the issue

To reproduce the issue I took the `posts` quickstart from the doc and I simply modified it to have a body made by a list of scalars.
1. Clone my sample repo: https://github.com/lampajr/kiota_posts
2. Run `kiota generate -l go -c PostsClient -n kiota_posts/client -d ./posts-api.yaml -o ./client`

[1] https://go.dev/wiki/InterfaceSlice

Pull request:
Fixes https://github.com/microsoft/kiota/issues/4380

Given openapi:
```yaml
    post:
      description: 'Create post'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: array
              items:
                format: int32
                type: integer
```

The expected `ToPostRequestInformation` would be:
```go
// ToPostRequestInformation create post
// returns a *RequestInformation when successful
func (m *PostsRequestBuilder) ToPostRequestInformation(ctx context.Context, body []int32, requestConfiguration *PostsRequestBuilderPostRequestConfiguration) (*i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestInformation, error) {
	requestInfo := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.NewRequestInformationWithMethodAndUrlTemplateAndPathParameters(i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.POST, "{+baseurl}/posts", m.BaseRequestBuilder.PathParameters)
	if requestConfiguration != nil {
		requestInfo.Headers.AddAll(requestConfiguration.Headers)
		requestInfo.AddRequestOptions(requestConfiguration.Options)
	}
	requestInfo.Headers.TryAdd("Accept", "application/json")
	cast := make([]interface{}, len(body))
	for i, v := range body {
		cast[i] = v
	}
	requestInfo.SetContentFromScalarCollection(ctx, m.BaseRequestBuilder.RequestAdapter, "application/json", cast)
	return requestInfo, nil
}
```

Note the array _cast_:

```go
	cast := make([]interface{}, len(body))
	for i, v := range body {
		cast[i] = v
	}
```

Which is requried as you cannot pass `[]int32` as `[]interface{}` without this trick.

Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 90a7c1d6d1..e109a7f170 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 
 ### Changed
 
+- Fixed Go generation bug when dealing with scalar collection body. [#4380](https://github.com/microsoft/kiota/issues/4380)
 - Fixed a bug where multiple Visual Studio Code instances would make the extension install/update fail. [#3686](https://github.com/microsoft/kiota/issues/3686)
 - Fixed a bug where models properties named "additionalData" or "backingstore" would be ignored. [#4224](https://github.com/microsoft/kiota/issues/4224)
 - PREVIEW: Renamed the config commands to workspace. [#4310](https://github.com/microsoft/kiota/issues/4310)
diff --git a/src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs
index 989c9df1d7..ebda6de8f3 100644
--- a/src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs
+++ b/src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs
@@ -723,16 +723,23 @@ private void WriteFieldDeserializer(CodeProperty property, LanguageWriter writer
     private static string GetTypeAssertion(string originalReference, string typeImportName, string? assignVarName = default, string? statusVarName = default) =>
         $"{assignVarName}{(!string.IsNullOrEmpty(statusVarName) && !string.IsNullOrEmpty(assignVarName) ? ", " : string.Empty)}{statusVarName}{(string.IsNullOrEmpty(statusVarName) && string.IsNullOrEmpty(assignVarName) ? string.Empty : " := ")}{originalReference}.({typeImportName})";
 
-    private static void WriteCollectionCast(string propertyTypeImportName, string sourceVarName, string targetVarName, LanguageWriter writer, string pointerSymbol = "*", bool dereference = true)
+    private static void WriteCollectionCast(string propertyTypeImportName, string sourceVarName, string targetVarName, LanguageWriter writer, string pointerSymbol = "*", bool dereference = true, bool scalar = false)
     {
         writer.WriteLines($"{targetVarName} := make([]{propertyTypeImportName}, len({sourceVarName}))",
             $"for i, v := range {sourceVarName} {{");
         writer.IncreaseIndent();
-        writer.StartBlock("if v != nil {");
-        var derefPrefix = dereference ? "*(" : string.Empty;
-        var derefSuffix = dereference ? ")" : string.Empty;
-        writer.WriteLine($"{targetVarName}[i] = {GetTypeAssertion(derefPrefix + "v", pointerSymbol + propertyTypeImportName)}{derefSuffix}");
-        writer.CloseBlock();
+        if (!scalar)
+        {
+            writer.StartBlock("if v != nil {");
+            var derefPrefix = dereference ? "*(" : string.Empty;
+            var derefSuffix = dereference ? ")" : string.Empty;
+            writer.WriteLine($"{targetVarName}[i] = {GetTypeAssertion(derefPrefix + "v", pointerSymbol + propertyTypeImportName)}{derefSuffix}");
+            writer.CloseBlock();
+        }
+        else
+        {
+            writer.WriteLine($"{targetVarName}[i] = v");
+        }
         writer.CloseBlock();
     }
 
@@ -909,7 +916,14 @@ private void WriteRequestGeneratorBody(CodeMethod codeElement, RequestParams req
                 writer.WriteBlock("if err != nil {", "}", "return nil, err");
             }
             else
+            {
+                if (requestParams.requestBody.Type.IsCollection)
+                {
+                    WriteCollectionCast("interface{}", bodyParamReference, "cast", writer, string.Empty, false, true);
+                    bodyParamReference = "cast";
+                }
                 writer.WriteLine($"{RequestInfoVarName}.SetContentFromScalar{collectionSuffix}({contextParameterName}, m.{requestAdapterPropertyName}, \"{sanitizedRequestBodyContentType}\", {bodyParamReference})");
+            }
         }
 
         writer.WriteLine($"return {RequestInfoVarName}, nil");


Test patch:
diff --git a/tests/Kiota.Builder.Tests/Writers/Go/CodeMethodWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Go/CodeMethodWriterTests.cs
index 54ded91a6e..46fc85c386 100644
--- a/tests/Kiota.Builder.Tests/Writers/Go/CodeMethodWriterTests.cs
+++ b/tests/Kiota.Builder.Tests/Writers/Go/CodeMethodWriterTests.cs
@@ -1168,6 +1168,7 @@ public async Task WritesRequestGeneratorBodyForScalar()
         Assert.Contains("if c.Q != nil", result);
         Assert.Contains("requestInfo.AddQueryParameters(", result);
         Assert.Contains("requestInfo.AddRequestOptions(", result);
+        Assert.DoesNotContain("cast[i] = v", result);
         Assert.Contains("requestInfo.SetContentFromScalar(ctx, m.BaseRequestBuilder.RequestAdapter", result);
         Assert.Contains("return requestInfo, nil", result);
         AssertExtensions.CurlyBracesAreClosed(result);
@@ -1205,6 +1206,8 @@ public async Task WritesRequestGeneratorBodyForScalarCollection()
         Assert.Contains("if c.Q != nil", result);
         Assert.Contains("requestInfo.AddQueryParameters(", result);
         Assert.Contains("requestInfo.AddRequestOptions(", result);
+        Assert.Contains("cast := make([]interface{}, ", result);
+        Assert.Contains("cast[i] = v", result);
         Assert.Contains("requestInfo.SetContentFromScalarCollection(ctx, m.BaseRequestBuilder.RequestAdapter", result);
         Assert.Contains("return requestInfo, nil", result);
         AssertExtensions.CurlyBracesAreClosed(result);
@@ -1305,6 +1308,7 @@ public async Task WritesRequestGeneratorBodyForParsableCollection()
         Assert.Contains("if c.Q != nil", result);
         Assert.Contains("requestInfo.AddQueryParameters(", result);
         Assert.Contains("requestInfo.AddRequestOptions(", result);
+        Assert.Contains("cast[i] =", result);
         Assert.Contains("requestInfo.SetContentFromParsableCollection(ctx, m.BaseRequestBuilder.RequestAdapter", result);
         Assert.Contains("return requestInfo, nil", result);
         AssertExtensions.CurlyBracesAreClosed(result);