![](/img/trans.png)
[英]How to get the string value of an HTTP header that I just set in Go?
[英]Go HTTP will not set header for SVG
我正在生成一个 SVG (它将在一个单独的浏览器 window 中加载,它检测到 header 是错误的),将内容类型设置为"image/svg+xml"
,然后写入 SVG,但是当它被发送到在浏览器中,它显示为text/xml
。
我先写了 header (这是本期的问题) ,漫无目的地移动了几个小时后,我失去了想法。
这是我的代码:
const circlesize = 2.5
// http.HandleFunc("/rendermap.svg", rendermapw)
func rendermapw(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.WriteHeader(405)
return
}
fmt.Println("Received request " + r.URL.String())
var mapstring string
// already rendered
if mapcache.valid {
mapstring = mapcache.cache
} else {
// get template
contentb, err := ioutil.ReadFile("src/maptemplate.svg")
if err != nil {
fmt.Println("Error with request:", r)
fmt.Println(err)
w.WriteHeader(500)
return
}
content := strings.Split(string(contentb), "<!--template-->")
// pull from database
alldata := *pullall()
mapstring = content[0] // header
for _, e := range alldata {
newcircle := content[1]
// string from uint64 (int64 from uint16)
newcircle = strings.Replace(newcircle, "{ulat}", strconv.FormatInt(int64(e.Ulat), 10), 1)
newcircle = strings.Replace(newcircle, "{ulon}", strconv.FormatInt(180-int64(e.Ulon), 10), 1)
newcircle = strings.Replace(newcircle, "{size}", strconv.FormatFloat(circlesize, 'f', 4, 64), 1)
mapstring += newcircle
}
mapstring += content[2]
// save cache & send
mapcache = mapcached{
valid: true,
cache: mapstring,
}
}
// everything above this works, I'm just posting it for completion's sake
w.WriteHeader(200)
w.Header().Set("content-type", "image/svg+xml")
_, err := fmt.Fprint(w, mapstring) // I also tried w.Write([]byte(mapstring))
if err != nil {
fmt.Println("Error with request:", r)
fmt.Println(err)
w.WriteHeader(500)
return
}
}
这是发送到浏览器的内容:
Content-Type: text/xml; charset=utf-8
这是maptemplate.svg
看起来像:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 360 180" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" fill="#0098ff">
<!--template-->
<circle cx="{ulat}" cy="{ulon}" r="{size}" fill-opacity=".5"/>
<!--template-->
</svg>
如果我删除 "<?xml version..." 行,浏览器将发送text/plain
。
我修好了它。 你必须在w.WriteHeader(200)
之前有w.Header().Set("content-type", "image/svg+xml")
) 。
工作代码:
// ...
w.Header().Set("content-type", "image/svg+xml")
w.WriteHeader(200)
_, err := fmt.Fprint(w, mapstring)
if err != nil {
fmt.Println("Error with request:", r)
fmt.Println(err)
w.WriteHeader(500)
return
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.