当我执行此go代码时,html代码显示时没有css,但是当我直接在浏览器中打开它时,它同时显示了html和css

package main

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

func main() {
    templates := template.Must(template.ParseFiles("templates/index.html"))

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        if err := templates.ExecuteTemplate(w, "index.html", nil); err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }

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

}

This is partially a total guess, but it seems like your html probably has something like:

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

When you open your html file directly in the browser, the browser is accessing a url like:

file:///path/to/your/html

and so it then is able to load:

file:///path/to/your/css/stylesheet.css

But when you do it in the browser, it tries to access

http://localhost/css/stylesheet.css

And you have no route to handle it in your app. So of course it doesn't find it. You probably need to set up a handler for serving your static files.

So I would move all of your static assets into a folder "assets", and then do:

func main() {
    templates := template.Must(template.ParseFiles("templates/index.html"))

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        if err := templates.ExecuteTemplate(w, "index.html", nil); err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }

    })
    fs := http.FileServer(http.Dir("assets"))
    http.Handle("/assets/", http.StripPrefix("/assets/", fs))
    log.Println("Listening...")
    fmt.Println(http.ListenAndServe(":8080", nil))

}

http.HandleFunc("/", serveTemplate)