Golang:CSS文件与Content-Type:text/plain一起发送

Nic*_*cci 2 css go server

我环顾四周,没有发现任何具体的东西.我正在使用Go的标准库构建API.在提供我的资源文件时,我的CSS文件会像text/plain我想要发送一样发送text/css.

控制台向我发出一条信息消息说:

Resource interpreted as Stylesheet but transferred with MIME type text/plain: "http://localhost:3000/css/app.css".

main.go

package main

import (
    "bufio"
    "log"
    "net/http"
    "os"
    "strings"
    "text/template"
)

func main() {
    templates := populateTemplates()

    http.HandleFunc("/",
        func(w http.ResponseWriter, req *http.Request) {
            requestedFile := req.URL.Path[1:]
            template := templates.Lookup(requestedFile + ".html")

            if template != nil {
                template.Execute(w, nil)
            } else {
                w.WriteHeader(404)
            }
        })

    http.HandleFunc("/img/", serveResource)
    http.HandleFunc("/css/", serveResource)

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

func serveResource(w http.ResponseWriter, req *http.Request) {
    path := "public" + req.URL.Path
    var contentType string
    if strings.HasSuffix(path, ".css") {
        contentType = "text/css"
    } else if strings.HasSuffix(path, ".png") {
        contentType = "image/png"
    } else {
        contentType = "text/plain"
    }

    f, err := os.Open(path)

    if err == nil {
        defer f.Close()
        w.Header().Add("Content Type", contentType)

        br := bufio.NewReader(f)
        br.WriteTo(w)
    } else {
        w.WriteHeader(404)
    }
}

func populateTemplates() *template.Template {
    result := template.New("templates")

    basePath := "templates"
    templateFolder, _ := os.Open(basePath)
    defer templateFolder.Close()

    templatePathRaw, _ := templateFolder.Readdir(-1)

    templatePaths := new([]string)
    for _, pathInfo := range templatePathRaw {
        if !pathInfo.IsDir() {
            *templatePaths = append(*templatePaths,
                basePath+"/"+pathInfo.Name())
        }
    }

    result.ParseFiles(*templatePaths...)

    return result
}
Run Code Online (Sandbox Code Playgroud)

我相信我发送它text/css.我看到这个错了吗?

Cer*_*món 7

应用程序在内容类型标题名称中缺少" - ".将代码更改为:

    w.Header().Add("Content-Type", contentType)
Run Code Online (Sandbox Code Playgroud)