Is TCPServer capable of responding to an incoming request? (OAuth2.0 authorization flow)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By a_world_of_madness

I’m implementing a plugin to interface with a web service’s REST API. The service uses OAuth2.0 for authorization, and I’m using the authorization code flow with PKCE, meaning I have to host a redirect server during the authorization to receive the authorization code.

I have succesfully implemented the whole authorization process, but when the user initially grants access on their browser, they are redirected to the Godot-hosted redirect server, which receives the authorization code.

Basically, I initialize the server:

var server : TCPServer = TCPServer.new()
server.listen(8080)

Then later when server.is_connection_available is true in a timer loop, I get the StreamPeerTCP:

var peer : StreamPeerTCP = server.take_connection()

I then get the chunk data, which contains the authorization code:

var data := peer.get_string(peer.get_available_bytes())

After this I don’t really need the StreamPeerTCP or the TCPServer anymore, so I close the peer connection with peer.disconnect_from_host, but this leaves the browser waiting for a response.

So, is there a way to respond to the request, for example with simply the response code 200?

I’ve tried the StreamPeerTCP methods put_utf8_stringand put_datawith ascii and utf8 strings, but those seem to not be the solution, as Insomnia responds with Error: Unsupported protocol

:bust_in_silhouette: Reply From: a_world_of_madness

Figured it out, turns out put_data works after all, I just needed to get the right syntax.

This allowed me to close the tab automatically:

var response := """HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8

<html>
	<head>
		<script>
			window.close()
		</script
	</head>
	<body>
	</body>
</html
"""
peer.put_data(response.to_utf8_buffer())
peer.disconnect_from_host()