Sam Wood
Sam Wood

Reputation: 418

Нow to serve an HTML web page while rendering the CSS styling from an external stylesheet - styles being ignored

I'm trying to write a very basic web server which serves a single static web page with basic css styling.

So request made to "/", then the index.html page gets displayed - WITH it's styling.

Problem: The index.html page gets displayed but the styling does not get... "applied" - it just seems to ignore it.

I have seen 3-5 other similar questions on here, none of which helped. They all suggest using a "FileServer" which wasn't ever explained. I just want to display the html page with it's styling. I don't understand why we need a file server to render a HTML page with some styling.

I can achieve this in Python using flask very simply by saying "return render_template()".

server.go:

package main

import (
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", indexHandler)

    log.Fatal(http.ListenAndServe(":8081", nil))
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "index.html")
    return
}

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sam Wood | Simple Go Web Server</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Simple Go Web Server</h1>
</body>
</html>
* {
    margin: 0;
    padding: 0;
    border: 0;
    box-sizing: border-box;
}

body {
    background-color: coral;
    color: cadetblue;
}

Upvotes: 0

Views: 57

Answers (1)

user15190760
user15190760

Reputation:

You need to make sure you serve the css file for the browser to download it from your server when it renders the HTML page.

In the code, you need to have two http.Handle* calls. Frankly, I don't know how to do this where the files are not in directories.

/html/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sam Wood | Simple Go Web Server v1.1 </title>
    <link rel="stylesheet" href="/css/style.css"> <!-- Emphasis here /css/style.css -->
</head>
<body>
    <h1>Simple Go Web Server v1.1</h1>
</body>
</html>

/static/css/style.css

(Same as your code above)

/main.go

package main

import (
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", indexHandler)
    http.Handle("/css/", http.FileServer(http.Dir("static"))) // This is where we can tell go to serve the files in the static/css/ directory

    log.Fatal(http.ListenAndServe(":8081", nil))
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "./html/index.html")
    return
}

Upvotes: 1

Related Questions