英文:
Why does fmt.Fprintf with an http.ResponseWriter not work for a css file?
问题
当我这样提供一个css文件时:
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
b, _ := ioutil.ReadFile("style1.css") // 7626字节
bigString := string(b)
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Type", "text/css")
writer.Header().Set("Connection", "keep-alive")
writer.Header().Set("Content-Length", fmt.Sprintf("%d", len(bigString)))
fmt.Fprintf(writer, bigString)
})
log.Fatal(http.ListenAndServe(":3000", nil))
}
当我使用curl http://localhost:3000/时,我得到以下错误:
curl: (18) transfer closed with 7626 bytes remaining to read
但是,如果我将fmt.Fprintf
更改为:
writer.Write([]byte(bigString))
它就可以正常工作了。我花了几个小时来调试,发现是因为fmt.Fprintf
导致我的css文件无法正确加载。
英文:
When I serve a css file like so:
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
b, _ := ioutil.ReadFile("style1.css") // 7626 bytes
bigString := string(b)
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Type", "text/css")
writer.Header().Set("Connection", "keep-alive")
writer.Header().Set("Content-Length", fmt.Sprintf("%d", len(bigString)))
fmt.Fprintf(writer, bigString)
})
log.Fatal(http.ListenAndServe(":3000", nil))
}
and I curl http://localhost:3000/ I get:
curl: (18) transfer closed with 7626 bytes remaining to read
but if I just change the fmt.Fprintf like to:
writer.Write([]byte(bigString))
it works fine. This took me hours to debug, my css file would not load right all because of fmt.Fprintf.
答案1
得分: 1
这是要翻译的内容:
https://pkg.go.dev/fmt#Fprintf
这将查找类似于%s或%d的内容,并尝试执行常规的printf操作!
在一个css文件中,我有一些%字符,它们在最终结果中丢失了,或者导致curl传输关闭。
英文:
https://pkg.go.dev/fmt#Fprintf
This will look for stuff like %s or %d and try and do normal printf stuff!
With a css file I had % chars in it and they were missing from the end result or causing the curl transfer closed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论