du131642 2016-03-31 02:44
浏览 119
已采纳

Golang:正在以Content-Type发送文本的CSS文件:纯文本/纯文本[关闭]

I have looked around and haven't found anything specific for what I am after. I am building an API using Go's standard library. When serving up my resource files, my CSS files are sent as text/plain when I am wanting to send it as text/css.

The console throws an info message at me saying:

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
}

I believe I am sending it as text/css. Am I seeing this wrong?

  • 写回答

1条回答 默认 最新

  • doushi9474 2016-03-31 02:47
    关注

    The application is missing a "-" in the content type header name. Change the code to:

        w.Header().Add("Content-Type", contentType)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?