improvement: use mimetype class & get rid of warnings

This commit is contained in:
xananax prozaxx 2022-06-25 10:56:45 +02:00
parent 5380b59ee2
commit 003eb04013

47
Main.gd
View File

@ -1,15 +1,6 @@
extends Control extends Control
const mime_types: Dictionary = { var mime_types := MimeTypeHelper.generate_db()
"html": "text/html",
"htm": "text/html",
"md": "text/plain",
"css": "text/css",
"txt": "text/plain",
"png": "image/png",
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
}
var _server: HTTPServer = null var _server: HTTPServer = null
@ -27,7 +18,9 @@ func _start_server(port: int = 3001) -> void:
_server = HTTPServer.new() _server = HTTPServer.new()
var dir := Directory.new() var dir := Directory.new()
if dir.open("res://server_files") == OK: if dir.open("res://server_files") == OK:
dir.list_dir_begin() if dir.list_dir_begin() != OK:
# TODO: show error to user here
return
var file_name := dir.get_next() var file_name := dir.get_next()
while file_name != "": while file_name != "":
if !dir.current_is_dir(): if !dir.current_is_dir():
@ -44,7 +37,9 @@ func _start_server(port: int = 3001) -> void:
_server.endpoint(HTTPServer.Method.GET, "/", funcref(self, "_serve_file"), ["index.html"]) _server.endpoint(HTTPServer.Method.GET, "/", funcref(self, "_serve_file"), ["index.html"])
_server.listen(port) if _server.listen(port) != OK:
# TODO: show error to user here
return
func _stop_server() -> void: func _stop_server() -> void:
@ -56,24 +51,32 @@ func _process(_delta: float) -> void:
if _server == null: if _server == null:
return return
_server.take_connection() if not _server.take_connection():
# TODO: show error to user here
return
func _serve_file(request: HTTPServer.Request, response: HTTPServer.Response, binds: Array) -> void: func _serve_file(_request: HTTPServer.Request, response: HTTPServer.Response, binds: Array) -> void:
var file_name: String = binds[0] as String var file_name: String = binds[0] as String
print(file_name) print(file_name)
var f = File.new() var f := File.new()
f.open("res://server_files/%s" % file_name, File.READ) var success = f.open("res://server_files/%s" % file_name, File.READ)
var mime = get_mime_type(file_name) if success == OK:
response.header("content-type", get_mime_type(file_name)) var mime := mime_types.get(file_name)
response.header("content-type", mime.full_type)
response.data(f.get_as_text()) # variant
# else: # warning-ignore:incompatible_ternary
# response.header("content-type", "text/plain") var data = f.get_as_text() if mime.type == 'text' else f.get_buffer(f.get_len())
# response.data("500 - Read Error")
response.data(data)
else:
response.header("content-type", "text/plain")
response.data("500 - Read Error")
func get_mime_type(file_name: String) -> String: func get_mime_type(file_name: String) -> String: