Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

Can't serve external CSS File in Go webapp

I recently started learning go and I want to develop a simple website. However I can't figure out how to use a external CSS File for this Website.

This is my directory structure:

./
  main.go
  static/
    css/
      home.css
  templates/
    home.html

Here is my main.go file:

package main

import (
        "html/template"
        "log"
        "net/http"
)

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

        fs := http.FileServer(http.Dir("static/"))
        http.Handle("/static/", http.StripPrefix("/static/", fs))

        log.Println("Listening on :8080...")
        log.Fatal(http.ListenAndServe(":8080", nil))
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
        renderTemplate(w, "home")
}

func renderTemplate(w http.ResponseWriter, tmpl string) {
        t, err := template.ParseFiles("templates/" + tmpl + ".html")
        if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                return
        }
        err = t.Execute(w, nil)
        if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
        }
}

And in home.html I added this in my header:

<link rel="stylesheet" href="/css/home.css">

When debugging in the browser it seems that the file is found, but there's an error with the MIME type: Browser Console Screenshot

I thought that this two lines would solve that, but apparently it doesn't:

fs := http.FileServer(http.Dir("static/"))
http.Handle("/static/", http.StripPrefix("/static/", fs))

Does somebody know what I am doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...