Search code examples
c++static-files

Serving static files with C++


I have own Web server implementation based on C++ TCP sockets. Now this server can send plain text in HTTP body. I need this server to send static files (HTML, CSS, JS). Files are located in ./static/ directory (./static/admin.html, ./static/admin.css, ./static/admin.js), server reads files contents and sends it to client with appropriate HTTP-headers. admin.html file has link to admin.css and admin.js, like it shown in the code below.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin Page</title>
    <link rel="stylesheet" type="text/css" href="admin.css">
</head>
<body>
    <script src="admin.js"></script>
    <!-- ... -->
</body>
</html>

1) How could client receive css and js files?

2) What is the common sense to serving static files?

2.1) Should I read *.html file to buffer, inject to the buffer contents of *.css in <style> tag and contents of *.js in <script> tag? Is there another more effective/elegant/good way?


Solution

    1. client will received .css and .js files but not the way you seem to think! When the client will request your html file it will parse it and will then find that it includes .css or .js, etc. So it will just ask for them separately in other requests. For this to work properly, you need to type the file sent back to client. Look for HTTP Header "Content-Type" (ex.: for HTML files you should type them as "Content-Type: text/html").
    2. not clear what you are asking for.
    3. certainly not, let the client do its job!