为什么使用`fmt.Fprintf`和`http.ResponseWriter`无法处理CSS文件?

huangapple go评论65阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年3月5日 23:46:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75643411.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定