tickle-godot-frontend/Main.gd

78 lines
1.8 KiB
GDScript3
Raw Normal View History

2022-06-21 12:48:14 +00:00
extends Control
var mime_types := MimeTypeHelper.generate_db()
2022-06-21 12:48:14 +00:00
var _server: HTTPServer = null
onready var server_ui := $ServerUI
onready var server_dir = server_ui.server_dir
2022-06-21 12:48:14 +00:00
func _ready() -> void:
pass
2022-06-21 12:48:14 +00:00
func _start_server(port: int = 3001) -> void:
if _server:
return
_server = HTTPServer.new()
2022-07-03 20:37:47 +00:00
_server.endpoint(HTTPServer.Method.GET, "/", funcref(self, "_serve_file"), ["index.html"]) # this is still needed to make 'localhost:port/' to point to index.html
_server.fallback(funcref(self, "_serve_file"))
2022-06-21 12:48:14 +00:00
if _server.listen(port) != OK:
# TODO: show error to user here
return
2022-06-21 12:48:14 +00:00
server_ui.is_server_running = true
2022-06-21 12:48:14 +00:00
func _stop_server() -> void:
if _server:
_server.stop()
2022-06-21 12:48:14 +00:00
_server = null
server_ui.is_server_running = false
2022-06-21 12:48:14 +00:00
func _process(_delta: float) -> void:
if _server == null:
return
if not _server.take_connection():
# TODO: show error to user here
return
2022-06-21 12:48:14 +00:00
func _serve_file(_request: HTTPServer.Request, response: HTTPServer.Response, binds: Array) -> void:
2022-06-21 12:48:14 +00:00
var file_name: String = binds[0] as String
2022-07-03 20:37:47 +00:00
# TODO: deprecate binds in favor of using the Request.endpoint prop, as for this app's purposes it would be the same as the file name
var f := File.new()
var success = f.open(server_dir.plus_file(file_name), File.READ)
2022-06-21 12:48:14 +00:00
2022-07-03 20:37:47 +00:00
if success == OK: # TODO: handle other errors like file not found
var mime := mime_types.get(file_name)
response.type(mime)
var data = f.get_buffer(f.get_len())
2022-06-21 12:48:14 +00:00
response.data(data)
else:
2022-07-03 20:37:47 +00:00
response.type(mime_types.get("txt"))
response.status(500)
response.data("Internal Server Error")
func _on_ServerUI_start_server_button_pressed(port: int, new_dir: String) -> void:
server_dir = new_dir
_start_server(port)
func _on_ServerUI_stop_server_button_pressed() -> void:
_stop_server()
func _on_ServerUI_server_folder_changed(new_path: String) -> void:
server_dir = new_path