Repository: aws/aws-sam-cli

Issue:
SAM cli 1.13.2+ Go debugging broken
<!-- Make sure we don't have an existing Issue that reports the bug you are seeing (both open and closed). 
If you do find an existing Issue, re-open or add a comment to that Issue instead of creating a new one. -->

### Description:
<!-- Briefly describe the bug you are facing.-->
Attempting to debug a go lambda with sam cli start-api/invoke makes the lambda code fail to start

### Steps to reproduce:
1. Create a sam app with these parameters using 1.13.2
```
    -----------------------
    Generating application:
    -----------------------
    Name: test113sam
    Runtime: go1.x
    Dependency Manager: mod
    Application Template: hello-world
    Output Directory: .

    Next steps can be found in the README file at ./test113sam/README.md
```
2. `sam build`
3. run `sam local invoke` it works fine:
```
$ sam local invoke
Invoking hello-world (go1.x)
Skip pulling image and use local one: amazon/aws-sam-cli-emulation-image-go1.x:rapid-1.13.2.

Mounting /private/tmp/test113sam/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
START RequestId: d1f12116-37df-4127-9b64-36aacdccea8c Version: $LATEST
END RequestId: d1f12116-37df-4127-9b64-36aacdccea8c
REPORT RequestId: d1f12116-37df-4127-9b64-36aacdccea8c	Init Duration: 1.57 ms	Duration: 785.02 ms	Billed Duration: 800 ms	Memory Size: 128 MB	Max Memory Used: 128 MB
{"statusCode":200,"headers":null,"multiValueHeaders":null,"body":"Hello, 72.21.198.67\n"}
```
Now, try invoking with Devle debugger args:
```
sam local invoke --debug-args -delveAPI=2 --debugger-path /Users/werlla/IdeaProjects/go1sam/ --debug-port 59394 --debug
2020-12-07 13:10:50,211 | Telemetry endpoint configured to be https://aws-serverless-tools-telemetry.us-west-2.amazonaws.com/metrics
2020-12-07 13:10:50,418 | local invoke command is called
2020-12-07 13:10:50,427 | No Parameters detected in the template
2020-12-07 13:10:50,454 | 2 resources found in the template
2020-12-07 13:10:50,455 | Found Serverless function with name='HelloWorldFunction' and CodeUri='HelloWorldFunction'
2020-12-07 13:10:50,464 | Found one Lambda function with name 'HelloWorldFunction'
2020-12-07 13:10:50,464 | Invoking hello-world (go1.x)
2020-12-07 13:10:50,464 | Environment variables overrides data is standard format
2020-12-07 13:10:50,464 | Loading AWS credentials from session with profile 'None'
2020-12-07 13:10:51,929 | Resolving code path. Cwd=/private/tmp/test113sam/.aws-sam/build, CodeUri=HelloWorldFunction
2020-12-07 13:10:51,929 | Resolved absolute path to code is /private/tmp/test113sam/.aws-sam/build/HelloWorldFunction
2020-12-07 13:10:51,930 | Code /private/tmp/test113sam/.aws-sam/build/HelloWorldFunction is not a zip/jar file
2020-12-07 13:10:53,185 | Failed to download image with name amazon/aws-sam-cli-emulation-image-go1.x:debug-1.13.2
2020-12-07 13:10:53,185 | Failed to download a new amazon/aws-sam-cli-emulation-image-go1.x:debug-1.13.2 image. Invoking with the already downloaded image.
2020-12-07 13:10:53,186 | Mounting /private/tmp/test113sam/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
2020-12-07 13:10:53,859 | Setting up SIGTERM interrupt handler
2020/12/07 21:10:53 Error starting mock server: fork/exec /var/rapid/init: no such file or directory
2020-12-07 13:10:54,710 | No response from invoke container for HelloWorldFunction
2020-12-07 13:10:54,711 | Sending Telemetry: {'metrics': [{'commandRun': {'awsProfileProvided': False, 'debugFlagProvided': True, 'region': '', 'commandName': 'sam local invoke', 'duration': 4498, 'exitReason': 'success', 'exitCode': 0, 'requestId': 'fd63fac1-9b23-4de9-a4ab-e6b76e979b13', 'installationId': '8e36c82e-d3f0-45b7-9e48-1e6f0ad535a6', 'sessionId': '10201463-def2-41d3-97ea-e2c5b3ee5e6f', 'executionEnvironment': 'CLI', 'pyversion': '3.8.6', 'samcliVersion': '1.13.2'}}]}
2020-12-07 13:10:54,880 | Telemetry response: 200
```


### Observed result:
<!-- Please provide command output with `--debug` flag set.-->
```
2020/12/07 21:10:53 Error starting mock server: fork/exec /var/rapid/init: no such file or directory
```
And it does not start. 
```
sam local invoke --debug-args "-delveAPI=2" --debugger-path /Users/werlla/IdeaProjects/go1sam/ --debug-port 59394 --debug
```
Quoting debug args results in the same output, and single quoting debug args leads to some more strange output without it running 
```
 sam local invoke --debug-args '-delveAPI=2' --debugger-path /Users/werlla/IdeaProjects/go1sam/ --debug-port 59394 --debug
2020-12-07 13:15:41,148 | Telemetry endpoint configured to be https://aws-serverless-tools-telemetry.us-west-2.amazonaws.com/metrics
2020-12-07 13:15:41,541 | local invoke command is called
2020-12-07 13:15:41,548 | No Parameters detected in the template
2020-12-07 13:15:41,589 | 2 resources found in the template
2020-12-07 13:15:41,589 | Found Serverless function with name='HelloWorldFunction' and CodeUri='HelloWorldFunction'
2020-12-07 13:15:41,608 | Found one Lambda function with name 'HelloWorldFunction'
2020-12-07 13:15:41,608 | Invoking hello-world (go1.x)
2020-12-07 13:15:41,608 | Environment variables overrides data is standard format
2020-12-07 13:15:41,609 | Loading AWS credentials from session with profile 'None'
2020-12-07 13:15:43,363 | Resolving code path. Cwd=/private/tmp/test113sam/.aws-sam/build, CodeUri=HelloWorldFunction
2020-12-07 13:15:43,363 | Resolved absolute path to code is /private/tmp/test113sam/.aws-sam/build/HelloWorldFunction
2020-12-07 13:15:43,363 | Code /private/tmp/test113sam/.aws-sam/build/HelloWorldFunction is not a zip/jar file
2020-12-07 13:15:44,558 | Failed to download image with name amazon/aws-sam-cli-emulation-image-go1.x:debug-1.13.2
2020-12-07 13:15:44,558 | Failed to download a new amazon/aws-sam-cli-emulation-image-go1.x:debug-1.13.2 image. Invoking with the already downloaded image.
2020-12-07 13:15:44,558 | Mounting /private/tmp/test113sam/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
2020-12-07 13:15:45,629 | Setting up SIGTERM interrupt handler
2020-12-07 13:15:46,391 | No response from invoke container for HelloWorldFunction
2020-12-07 13:15:46,392 | Sending Telemetry: {'metrics': [{'commandRun': {'awsProfileProvided': False, 'debugFlagProvided': True, 'region': '', 'commandName': 'sam local invoke', 'duration': 5242, 'exitReason': 'success', 'exitCode': 0, 'requestId': '61ed57b7-4d4d-4081-b4b7-88af18a3ec2f', 'installationId': '8e36c82e-d3f0-45b7-9e48-1e6f0ad535a6', 'sessionId': 'a568cab5-a111-40a0-bfef-a9800ec0a2a4', 'executionEnvironment': 'CLI', 'pyversion': '3.8.6', 'samcliVersion': '1.13.2'}}]}
2020-12-07 13:15:46,521 | Telemetry response: 200
```

### Expected result:
<!-- Describe what you expected.-->

Running with the same arguments starts correctly with sam cli `1.12.0`

### Additional environment details (Ex: Windows, Mac, Amazon Linux etc)

1. OS: Mac
2. `sam --version`: SAM CLI, version 1.13.2



Discussion:
I'm also seeing this issue. I've set up the hello-world via sam init and pretty much did the same commands as above.
So that is exactly the usecase which is described in the docs on how to debug with go.

Downgrading to v1.12.0 worked for me(Had to reinstall via pip `pip3 install --user 'aws-sam-cli==1.12.0'`)  
Some initial findings:

In https://github.com/aws/aws-sam-cli/pull/2425, the file `/local/rapid/init` was changed to `/local/rapid/aws-lambda-rie`, while in “samcli/local/go-bootstrap/aws-lambda-mock.go:96” `rapid/init` is still used.

This can be easily fixed in #2544. However, with #2544, we see a new error:

```
2021/01/20 00:50:48 http: panic serving 127.0.0.1:49540: &{0xc0001c8000 map[] 2021-01-20 00:50:48.4458573 +0000 UTC m=+0.017114501 panic <nil> ReplyStream not available <nil> <nil> }
goroutine 35 [running]:
net/http.(*conn).serve.func1(0xc0002880a0)
	/usr/local/go/src/net/http/server.go:1800 +0x139
panic(0x866640, 0xc0002cc150)
	/usr/local/go/src/runtime/panic.go:975 +0x3e3
github.com/sirupsen/logrus.Entry.log(0xc0001c8000, 0xc0002845a0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ...)
	/go/pkg/mod/github.com/sirupsen/logrus@v1.6.0/entry.go:259 +0x335
```

(full text: [1611104121.txt](https://github.com/aws/aws-sam-cli/files/5840043/1611104121.txt))

We narrow the cause to the same PR (#2425, commit SHA: 12efe15b682926b006ce2a846d7cc6c71f5f2d74).

* with 12efe1 and 2544 fix, we have this error when running `local invoke` with delve debugger.
* without 12efe1, everything works fine.

### How to reproduce the (new) error?

(See our official guide ["Step-through debugging Lambda functions locally"](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-debugging.html) for full details)
0. check out #2544, which contains the fix of the original error.
1. Install delve ([on macOS](https://github.com/go-delve/delve/blob/master/Documentation/installation/osx/install.md)), assuming it is install to `/Users/xxx/go/bin/dlv`.
2. build the hello world project with `sam build`
3. `sam local invoke`, now it works with or without 12efe1
4. `sam local invoke --debug-args -delveAPI=2 --debugger-path /Users/xxx/go/bin/ --debug-port 59394 --debug`, the error above shows up.

We have a guess: `aws-lambda-mock.go` does not play nicely with the new `aws-lambda-rie`. The error message is not very helpful, we need to isolate what inputs to the lambda container cause this problem by doing some experiments.

We found the issue and working on developing a fix. If you need this feature urgently, you can try the workaround #2548.

```sh
git clone git@github.com:aws/aws-sam-cli.git
cd aws-sam-cli
git pull origin pull/2548/head
python3 -m venv .env
source .env/bin/activate
make init 
# then you can use samdev to replace sam for local invoking
samdev local invoke --debug-args "--api-version=2 --log" --debugger-path <delve-directory> --debug-port 5986 --debug
```

Resolving patch:
diff --git a/samcli/local/docker/lambda_container.py b/samcli/local/docker/lambda_container.py
--- a/samcli/local/docker/lambda_container.py
+++ b/samcli/local/docker/lambda_container.py
@@ -2,11 +2,12 @@
 Represents Lambda runtime containers.
 """
 import logging
+from typing import List
 
 from samcli.local.docker.lambda_debug_settings import LambdaDebugSettings
 from samcli.lib.utils.packagetype import IMAGE
 from .container import Container
-from .lambda_image import Runtime
+from .lambda_image import Runtime, LambdaImage
 
 LOG = logging.getLogger(__name__)
 
@@ -77,7 +78,7 @@ def __init__(
         if not Runtime.has_value(runtime) and not packagetype == IMAGE:
             raise ValueError("Unsupported Lambda runtime {}".format(runtime))
 
-        image = LambdaContainer._get_image(lambda_image, runtime, packagetype, imageuri, layers, debug_options)
+        image = LambdaContainer._get_image(lambda_image, runtime, packagetype, imageuri, layers)
         ports = LambdaContainer._get_exposed_ports(debug_options)
         config = LambdaContainer._get_config(lambda_image, image)
         entry, container_env_vars = LambdaContainer._get_debug_settings(runtime, debug_options)
@@ -181,7 +182,7 @@ def _get_additional_volumes(runtime, debug_options):
         return volumes
 
     @staticmethod
-    def _get_image(lambda_image, runtime, packagetype, image, layers, debug_options):
+    def _get_image(lambda_image: LambdaImage, runtime: str, packagetype: str, image: str, layers: List[str]):
         """
         Returns the name of Docker Image for the given runtime
 
@@ -199,8 +200,7 @@ def _get_image(lambda_image, runtime, packagetype, image, layers, debug_options)
         str
             Name of Docker Image for the given runtime
         """
-        is_debug = bool(debug_options and debug_options.debugger_path)
-        return lambda_image.build(runtime, packagetype, image, layers, is_debug)
+        return lambda_image.build(runtime, packagetype, image, layers)
 
     @staticmethod
     def _get_config(lambda_image, image):
diff --git a/samcli/local/docker/lambda_debug_settings.py b/samcli/local/docker/lambda_debug_settings.py
--- a/samcli/local/docker/lambda_debug_settings.py
+++ b/samcli/local/docker/lambda_debug_settings.py
@@ -3,7 +3,9 @@
 """
 
 import logging
+from argparse import ArgumentParser
 from collections import namedtuple
+from typing import List, cast
 
 from samcli.local.docker.lambda_image import Runtime
 
@@ -88,10 +90,14 @@ def get_debug_settings(debug_port, debug_args_list, _container_env_vars, runtime
                 container_env_vars={"_AWS_LAMBDA_DOTNET_DEBUGGING": "1", **_container_env_vars},
             ),
             Runtime.go1x.value: DebugSettings(
-                ["/var/runtime/aws-lambda-go"]
-                + debug_args_list
-                + ["-debug=true", "-delvePort=" + str(debug_port), "-delvePath=" + options.get("delvePath")],
-                container_env_vars=_container_env_vars,
+                entry,
+                container_env_vars={
+                    "_AWS_LAMBDA_GO_DEBUGGING": "1",
+                    "_AWS_LAMBDA_GO_DELVE_API_VERSION": LambdaDebugSettings.parse_go_delve_api_version(debug_args_list),
+                    "_AWS_LAMBDA_GO_DELVE_LISTEN_PORT": debug_port,
+                    "_AWS_LAMBDA_GO_DELVE_PATH": options.get("delvePath"),
+                    **_container_env_vars,
+                },
             ),
             Runtime.nodejs10x.value: DebugSettings(
                 entry
@@ -143,3 +149,12 @@ def get_debug_settings(debug_port, debug_args_list, _container_env_vars, runtime
                 LOG.debug("Passing entrypoint as specified in template")
                 return DebugSettings(entry + debug_args_list, _container_env_vars)
             raise DebuggingNotSupported("Debugging is not currently supported for {}".format(runtime)) from ex
+
+    @staticmethod
+    def parse_go_delve_api_version(debug_args_list: List[str]) -> int:
+        parser = ArgumentParser("Parser for delve args")
+        parser.add_argument("-delveApi", type=int, default=1)
+        args, unknown_args = parser.parse_known_args(debug_args_list)
+        if unknown_args:
+            LOG.info("Ignoring unrecognized arguments: %s", unknown_args)
+        return cast(int, args.delveApi)
diff --git a/samcli/local/docker/lambda_image.py b/samcli/local/docker/lambda_image.py
--- a/samcli/local/docker/lambda_image.py
+++ b/samcli/local/docker/lambda_image.py
@@ -56,7 +56,6 @@ class LambdaImage:
     _INVOKE_REPO_PREFIX = "amazon/aws-sam-cli-emulation-image"
     _SAM_CLI_REPO_NAME = "samcli/lambda"
     _RAPID_SOURCE_PATH = Path(__file__).parent.joinpath("..", "rapid").resolve()
-    _GO_BOOTSTRAP_PATH = Path(__file__).parent.joinpath("..", "go-bootstrap").resolve()
 
     def __init__(self, layer_downloader, skip_pull_image, force_image_build, docker_client=None):
         """
@@ -77,7 +76,7 @@ def __init__(self, layer_downloader, skip_pull_image, force_image_build, docker_
         self.force_image_build = force_image_build
         self.docker_client = docker_client or docker.from_env()
 
-    def build(self, runtime, packagetype, image, layers, is_debug, stream=None):
+    def build(self, runtime, packagetype, image, layers, stream=None):
         """
         Build the image if one is not already on the system that matches the runtime and layers
 
@@ -124,9 +123,6 @@ def build(self, runtime, packagetype, image, layers, is_debug, stream=None):
             image_tag = f"{self._SAM_CLI_REPO_NAME}:{docker_image_version}"
 
         image_not_found = False
-        is_debug_go = runtime == "go1.x" and is_debug
-        if is_debug_go:
-            image_tag = f"{self._INVOKE_REPO_PREFIX}-{runtime}:debug-{version}"
 
         # If we are not using layers, build anyways to ensure any updates to rapid get added
         try:
@@ -144,9 +140,7 @@ def build(self, runtime, packagetype, image, layers, is_debug, stream=None):
             stream_writer = stream or StreamWriter(sys.stderr)
             stream_writer.write("Building image...")
             stream_writer.flush()
-            self._build_image(
-                image if image else image_name, image_tag, downloaded_layers, is_debug_go, stream=stream_writer
-            )
+            self._build_image(image if image else image_name, image_tag, downloaded_layers, stream=stream_writer)
 
         return image_tag
 
@@ -186,7 +180,7 @@ def _generate_docker_image_version(layers, runtime):
             runtime + "-" + hashlib.sha256("-".join([layer.name for layer in layers]).encode("utf-8")).hexdigest()[0:25]
         )
 
-    def _build_image(self, base_image, docker_tag, layers, is_debug_go, stream=None):
+    def _build_image(self, base_image, docker_tag, layers, stream=None):
         """
         Builds the image
 
@@ -208,7 +202,7 @@ def _build_image(self, base_image, docker_tag, layers, is_debug_go, stream=None)
         samcli.commands.local.cli_common.user_exceptions.ImageBuildException
             When docker fails to build the image
         """
-        dockerfile_content = self._generate_dockerfile(base_image, layers, is_debug_go)
+        dockerfile_content = self._generate_dockerfile(base_image, layers)
 
         # Create dockerfile in the same directory of the layer cache
         dockerfile_name = "dockerfile_" + str(uuid.uuid4())
@@ -222,10 +216,6 @@ def _build_image(self, base_image, docker_tag, layers, is_debug_go, stream=None)
             # add dockerfile and rapid source paths
             tar_paths = {str(full_dockerfile_path): "Dockerfile", self._RAPID_SOURCE_PATH: "/aws-lambda-rie"}
 
-            if is_debug_go:
-                LOG.debug("Adding custom GO Bootstrap to support debugging")
-                tar_paths[self._GO_BOOTSTRAP_PATH] = "/aws-lambda-go"
-
             for layer in layers:
                 tar_paths[layer.codeuri] = "/" + layer.name
 
@@ -257,7 +247,7 @@ def set_item_permission(tar_info):
                 full_dockerfile_path.unlink()
 
     @staticmethod
-    def _generate_dockerfile(base_image, layers, is_debug_go):
+    def _generate_dockerfile(base_image, layers):
         """
         Generate the Dockerfile contents
 
@@ -288,11 +278,6 @@ def _generate_dockerfile(base_image, layers, is_debug_go):
             f"FROM {base_image}\nADD aws-lambda-rie /var/rapid\nRUN chmod +x /var/rapid/aws-lambda-rie\n"
         )
 
-        if is_debug_go:
-            dockerfile_content = (
-                dockerfile_content + "ADD aws-lambda-go /var/runtime\nRUN chmod +x /var/runtime/aws-lambda-go\n"
-            )
-
         for layer in layers:
             dockerfile_content = dockerfile_content + f"ADD {layer.name} {LambdaImage._LAYERS_DIR}\n"
         return dockerfile_content


Test patch:
diff --git a/tests/unit/local/docker/test_lambda_container.py b/tests/unit/local/docker/test_lambda_container.py
--- a/tests/unit/local/docker/test_lambda_container.py
+++ b/tests/unit/local/docker/test_lambda_container.py
@@ -28,6 +28,7 @@
     Runtime.java8al2.value,
     Runtime.dotnetcore21.value,
     Runtime.dotnetcore31.value,
+    Runtime.go1x.value,
 ]
 
 RUNTIMES_WITH_ENTRYPOINT_OVERRIDES = RUNTIMES_WITH_ENTRYPOINT + RUNTIMES_WITH_BOOTSTRAP_ENTRYPOINT
@@ -102,9 +103,7 @@ def test_must_configure_container_properly_zip(
         self.assertEqual(expected_env_vars, container._env_vars)
         self.assertEqual(self.memory_mb, container._memory_limit_mb)
 
-        get_image_mock.assert_called_with(
-            image_builder_mock, self.runtime, self.packagetype, self.imageuri, [], self.debug_options
-        )
+        get_image_mock.assert_called_with(image_builder_mock, self.runtime, self.packagetype, self.imageuri, [])
         get_exposed_ports_mock.assert_called_with(self.debug_options)
         get_debug_settings_mock.assert_called_with(self.runtime, self.debug_options)
         get_additional_options_mock.assert_called_with(self.runtime, self.debug_options)
@@ -172,9 +171,7 @@ def test_must_configure_container_properly_image_no_debug(
         self.assertEqual({**expected_env_vars, **{"AWS_LAMBDA_FUNCTION_HANDLER": "mycommand"}}, container._env_vars)
         self.assertEqual(self.memory_mb, container._memory_limit_mb)
 
-        get_image_mock.assert_called_with(
-            image_builder_mock, self.runtime, self.packagetype, self.imageuri, [], self.debug_options
-        )
+        get_image_mock.assert_called_with(image_builder_mock, self.runtime, self.packagetype, self.imageuri, [])
         get_exposed_ports_mock.assert_called_with(self.debug_options)
         get_additional_options_mock.assert_called_with(self.runtime, self.debug_options)
         get_additional_volumes_mock.assert_called_with(self.runtime, self.debug_options)
@@ -245,9 +242,7 @@ def test_must_configure_container_properly_image_debug(
         self.assertEqual(expected_env_vars, container._env_vars)
         self.assertEqual(self.memory_mb, container._memory_limit_mb)
 
-        get_image_mock.assert_called_with(
-            image_builder_mock, self.runtime, IMAGE, self.imageuri, [], self.debug_options
-        )
+        get_image_mock.assert_called_with(image_builder_mock, self.runtime, IMAGE, self.imageuri, [])
         get_exposed_ports_mock.assert_called_with(self.debug_options)
         get_additional_options_mock.assert_called_with(self.runtime, self.debug_options)
         get_additional_volumes_mock.assert_called_with(self.runtime, self.debug_options)
@@ -320,9 +315,7 @@ def test_must_configure_container_properly_image_with_imageconfig_debug(
         )
         self.assertEqual(self.memory_mb, container._memory_limit_mb)
 
-        get_image_mock.assert_called_with(
-            image_builder_mock, self.runtime, IMAGE, self.imageuri, [], self.debug_options
-        )
+        get_image_mock.assert_called_with(image_builder_mock, self.runtime, IMAGE, self.imageuri, [])
         get_exposed_ports_mock.assert_called_with(self.debug_options)
         get_additional_options_mock.assert_called_with(self.runtime, self.debug_options)
         get_additional_volumes_mock.assert_called_with(self.runtime, self.debug_options)
@@ -396,9 +389,7 @@ def test_must_configure_container_properly_image_with_imageconfig_no_debug(
         )
         self.assertEqual(self.memory_mb, container._memory_limit_mb)
 
-        get_image_mock.assert_called_with(
-            image_builder_mock, self.runtime, self.packagetype, self.imageuri, [], self.debug_options
-        )
+        get_image_mock.assert_called_with(image_builder_mock, self.runtime, self.packagetype, self.imageuri, [])
         get_exposed_ports_mock.assert_called_with(self.debug_options)
         get_additional_options_mock.assert_called_with(self.runtime, self.debug_options)
         get_additional_volumes_mock.assert_called_with(self.runtime, self.debug_options)
@@ -461,10 +452,8 @@ def test_must_skip_if_port_is_not_given(self):
 
 
 class TestLambdaContainer_get_image(TestCase):
-    def test_must_return_lambci_image_with_debug(self):
-        debug_options = DebugContext(debug_ports=[1235], debugger_path="a", debug_args="a=b c=d e=f")
-
-        expected = "lambci/lambda:foo"
+    def test_must_return_build_image(self):
+        expected = "amazon/aws-sam-cli-emulation-image-foo:rapid-x.y.z"
 
         image_builder = Mock()
         image_builder.build.return_value = expected
@@ -476,34 +465,11 @@ def test_must_return_lambci_image_with_debug(self):
                 packagetype=ZIP,
                 image=None,
                 layers=[],
-                debug_options=debug_options,
             ),
             expected,
         )
 
-        image_builder.build.assert_called_with("foo", ZIP, None, [], True)
-
-    def test_must_return_lambci_image_without_debug(self):
-        debug_options = DebugContext()
-
-        expected = "lambci/lambda:foo"
-
-        image_builder = Mock()
-        image_builder.build.return_value = expected
-
-        self.assertEqual(
-            LambdaContainer._get_image(
-                lambda_image=image_builder,
-                runtime="foo",
-                packagetype=ZIP,
-                image=None,
-                layers=[],
-                debug_options=debug_options,
-            ),
-            expected,
-        )
-
-        image_builder.build.assert_called_with("foo", ZIP, None, [], False)
+        image_builder.build.assert_called_with("foo", ZIP, None, [])
 
 
 class TestLambdaContainer_get_debug_settings(TestCase):
@@ -544,17 +510,6 @@ def test_must_provide_container_env_vars(self, runtime):
 
         self.assertIsNotNone(container_env_vars)
 
-    @parameterized.expand([param(r) for r in set(RUNTIMES_WITH_ENTRYPOINT) if not r.startswith("dotnetcore")])
-    def test_debug_arg_must_be_split_by_spaces_and_appended_to_entrypoint(self, runtime):
-        """
-        Debug args list is appended starting at second position in the array
-        """
-        expected_debug_args = ["a=b", "c=d", "e=f"]
-        result, _ = LambdaContainer._get_debug_settings(runtime, self.debug_options)
-        actual = result[1:4]
-
-        self.assertEqual(actual, expected_debug_args)
-
     @parameterized.expand([param(r) for r in set(RUNTIMES_WITH_BOOTSTRAP_ENTRYPOINT)])
     def test_debug_arg_must_be_split_by_spaces_and_appended_to_bootstrap_based_entrypoint(self, runtime):
         """
@@ -573,6 +528,13 @@ def test_must_provide_entrypoint_even_without_debug_args(self, runtime):
 
         self.assertIsNotNone(result)
 
+    @parameterized.expand([(2, "-delveApi=2"), (2, "-delveApi 2"), (1, None)])
+    def test_delve_api_version_can_be_read_from_debug_args(self, version, debug_args):
+        debug_options = DebugContext(debug_ports=[1235], debug_args=debug_args)
+        _, env_vars = LambdaContainer._get_debug_settings(Runtime.go1x.value, debug_options)
+
+        self.assertEqual(env_vars.get("_AWS_LAMBDA_GO_DELVE_API_VERSION"), version)
+
 
 class TestLambdaContainer_get_additional_options(TestCase):
     def test_no_additional_options_when_debug_options_is_none(self):
diff --git a/tests/unit/local/docker/test_lambda_image.py b/tests/unit/local/docker/test_lambda_image.py
--- a/tests/unit/local/docker/test_lambda_image.py
+++ b/tests/unit/local/docker/test_lambda_image.py
@@ -46,7 +46,7 @@ def test_building_image_with_no_runtime_only_image(self):
         lambda_image = LambdaImage(layer_downloader_mock, False, False, docker_client=docker_client_mock)
 
         self.assertEqual(
-            lambda_image.build(None, IMAGE, "mylambdaimage:v1", [], False),
+            lambda_image.build(None, IMAGE, "mylambdaimage:v1", []),
             f"mylambdaimage:rapid-{version}",
         )
 
@@ -67,14 +67,12 @@ def test_building_image_with_no_runtime_only_image_always_build(
         lambda_image = LambdaImage(layer_downloader_mock, False, False, docker_client=docker_client_mock)
 
         self.assertEqual(
-            lambda_image.build(None, IMAGE, "mylambdaimage:v1", ["mylayer"], False),
+            lambda_image.build(None, IMAGE, "mylambdaimage:v1", ["mylayer"]),
             f"mylambdaimage:rapid-{version}",
         )
 
         # No layers are added, because runtime is not defined.
-        build_image_patch.assert_called_once_with(
-            "mylambdaimage:v1", f"mylambdaimage:rapid-{version}", [], False, stream=ANY
-        )
+        build_image_patch.assert_called_once_with("mylambdaimage:v1", f"mylambdaimage:rapid-{version}", [], stream=ANY)
         # No Layers are added.
         layer_downloader_mock.assert_not_called()
 
@@ -86,9 +84,9 @@ def test_building_image_with_non_accpeted_package_type(self):
 
         lambda_image = LambdaImage(layer_downloader_mock, False, False, docker_client=docker_client_mock)
         with self.assertRaises(InvalidIntermediateImageError):
-            lambda_image.build("python3.6", "Non-accepted-packagetype", None, [], False)
+            lambda_image.build("python3.6", "Non-accepted-packagetype", None, [])
         with self.assertRaises(InvalidIntermediateImageError):
-            lambda_image.build("python3.6", None, None, [], False)
+            lambda_image.build("python3.6", None, None, [])
 
     def test_building_image_with_no_layers(self):
         docker_client_mock = Mock()
@@ -99,22 +97,10 @@ def test_building_image_with_no_layers(self):
         lambda_image = LambdaImage(layer_downloader_mock, False, False, docker_client=docker_client_mock)
 
         self.assertEqual(
-            lambda_image.build("python3.6", ZIP, None, [], False),
+            lambda_image.build("python3.6", ZIP, None, []),
             f"amazon/aws-sam-cli-emulation-image-python3.6:rapid-{version}",
         )
 
-    def test_building_image_with_go_debug(self):
-        docker_client_mock = Mock()
-        layer_downloader_mock = Mock()
-        setattr(layer_downloader_mock, "layer_cache", self.layer_cache_dir)
-        docker_client_mock.api.build.return_value = ["mock"]
-        lambda_image = LambdaImage(layer_downloader_mock, False, False, docker_client=docker_client_mock)
-
-        self.assertEqual(
-            lambda_image.build("go1.x", ZIP, None, [], True),
-            f"amazon/aws-sam-cli-emulation-image-go1.x:debug-{version}",
-        )
-
     @patch("samcli.local.docker.lambda_image.LambdaImage._build_image")
     @patch("samcli.local.docker.lambda_image.LambdaImage._generate_docker_image_version")
     def test_not_building_image_that_already_exists(self, generate_docker_image_version_patch, build_image_patch):
@@ -130,7 +116,7 @@ def test_not_building_image_that_already_exists(self, generate_docker_image_vers
         docker_client_mock.images.get.return_value = Mock()
 
         lambda_image = LambdaImage(layer_downloader_mock, False, False, docker_client=docker_client_mock)
-        actual_image_id = lambda_image.build("python3.6", ZIP, None, [layer_mock], False)
+        actual_image_id = lambda_image.build("python3.6", ZIP, None, [layer_mock])
 
         self.assertEqual(actual_image_id, "samcli/lambda:image-version")
 
@@ -155,7 +141,7 @@ def test_force_building_image_that_doesnt_already_exists(
         stream = io.StringIO()
 
         lambda_image = LambdaImage(layer_downloader_mock, False, True, docker_client=docker_client_mock)
-        actual_image_id = lambda_image.build("python3.6", ZIP, None, ["layers1"], False, stream=stream)
+        actual_image_id = lambda_image.build("python3.6", ZIP, None, ["layers1"], stream=stream)
 
         self.assertEqual(actual_image_id, "samcli/lambda:image-version")
 
@@ -166,7 +152,6 @@ def test_force_building_image_that_doesnt_already_exists(
             "amazon/aws-sam-cli-emulation-image-python3.6:latest",
             "samcli/lambda:image-version",
             ["layers1"],
-            False,
             stream=stream,
         )
 
@@ -186,7 +171,7 @@ def test_not_force_building_image_that_doesnt_already_exists(
         stream = io.StringIO()
 
         lambda_image = LambdaImage(layer_downloader_mock, False, False, docker_client=docker_client_mock)
-        actual_image_id = lambda_image.build("python3.6", ZIP, None, ["layers1"], False, stream=stream)
+        actual_image_id = lambda_image.build("python3.6", ZIP, None, ["layers1"], stream=stream)
 
         self.assertEqual(actual_image_id, "samcli/lambda:image-version")
 
@@ -197,7 +182,6 @@ def test_not_force_building_image_that_doesnt_already_exists(
             "amazon/aws-sam-cli-emulation-image-python3.6:latest",
             "samcli/lambda:image-version",
             ["layers1"],
-            False,
             stream=stream,
         )
 
@@ -228,19 +212,7 @@ def test_generate_dockerfile(self, docker_patch):
         layer_mock = Mock()
         layer_mock.name = "layer1"
 
-        self.assertEqual(LambdaImage._generate_dockerfile("python", [layer_mock], False), expected_docker_file)
-
-    @patch("samcli.local.docker.lambda_image.docker")
-    def test_generate_dockerfile_with_go_debug(self, docker_patch):
-        docker_client_mock = Mock()
-        docker_patch.from_env.return_value = docker_client_mock
-
-        expected_docker_file = "FROM python\nADD aws-lambda-rie /var/rapid\nRUN chmod +x /var/rapid/aws-lambda-rie\nADD aws-lambda-go /var/runtime\nRUN chmod +x /var/runtime/aws-lambda-go\nADD layer1 /opt\n"
-
-        layer_mock = Mock()
-        layer_mock.name = "layer1"
-
-        self.assertEqual(LambdaImage._generate_dockerfile("python", [layer_mock], True), expected_docker_file)
+        self.assertEqual(LambdaImage._generate_dockerfile("python", [layer_mock]), expected_docker_file)
 
     @patch("samcli.local.docker.lambda_image.create_tarball")
     @patch("samcli.local.docker.lambda_image.uuid")
@@ -270,7 +242,7 @@ def test_build_image(self, generate_dockerfile_patch, path_patch, uuid_patch, cr
         m = mock_open(dockerfile_mock)
         with patch("samcli.local.docker.lambda_image.open", m):
             LambdaImage(layer_downloader_mock, True, False, docker_client=docker_client_mock)._build_image(
-                "base_image", "docker_tag", [layer_version1], True
+                "base_image", "docker_tag", [layer_version1]
             )
 
         handle = m()
@@ -313,7 +285,7 @@ def test_build_image_fails_with_BuildError(
         with patch("samcli.local.docker.lambda_image.open", m):
             with self.assertRaises(ImageBuildException):
                 LambdaImage(layer_downloader_mock, True, False, docker_client=docker_client_mock)._build_image(
-                    "base_image", "docker_tag", [layer_version1], True
+                    "base_image", "docker_tag", [layer_version1]
                 )
 
         handle = m()
@@ -355,7 +327,7 @@ def test_build_image_fails_with_ApiError(
         with patch("samcli.local.docker.lambda_image.open", m):
             with self.assertRaises(ImageBuildException):
                 LambdaImage(layer_downloader_mock, True, False, docker_client=docker_client_mock)._build_image(
-                    "base_image", "docker_tag", [layer_version1], True
+                    "base_image", "docker_tag", [layer_version1]
                 )
 
         handle = m()