英文:
how to ignore content type with golang?
问题
有人可以告诉我如何在Go语言中忽略内容类型吗?我可以在Java中使用Jsoup的ignoreContentType方法,但是我找不到在Go语言中可以实现类似功能的方法。希望有人可以告诉我,谢谢。
import (
"fmt"
"net/http"
)
func main() {
resp, err := http.Get("http://example.com/")
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}
英文:
can somebody tell me how to ignore content type with go? I can invoke ignoreContentType method in Jsoup with java, but i can't find any method in go can do like that. Hope someone will tell me, thanks.
Connection.Response response = Jsoup.connect("http://example.com/")
.ignoreContentType(true)
.execute();
System.out.println(response.body());
答案1
得分: 0
Java中的jsoup的ignoreContentType
用于在解析响应时忽略文档的Content-Type
。
在Go语言中,ResponseWriter
默认会将Content-Type设置为将前512个字节的数据传递给DetectContentType
函数后的结果。
你可以实现自己的ResponseWriter
,在其中将自定义的Content-Type设置为""
,以忽略响应数据中可能存在的(可能不正确的)内容类型。
func (writer MyOwnResponseWriter) Write(data []byte) (int, error) {
writer.Header().Set("Content-Type", "")
return len(data), nil
}
JimB在评论中建议简单地设置自己的Content-Type,因为server.go
中包含以下内容:
// 如果Header中不包含Content-Type行,
// Write函数会将Content-Type设置为将前512个字节的数据传递给DetectContentType函数后的结果。
英文:
Java jsoup ignoreContentType
is there to ignore the document's Content-Type
when parsing the response.
The ResponseWriter
in Go will by default adds a Content-Type set to the result of passing the initial 512 bytes of written data to DetectContentType
.
You can implement your own ResponseWriter
where you set your own Content-Type
to ""
in order to ignore any (possibly incorrect) content type deduced from the Response's data.
func (writer MyOwnResponseWriter) Write(data []byte) (int, error) {
writer.Header().Set("Content-Type", "")
return len(data), nil
}
JimB suggests in the comments to simply set your own Content-Type, as server.go
includes:
//If the Header does not contain a Content-Type line,
// Write adds a Content-Type set to the result of
// passing the initial 512 bytes of written data toDetectContentType.
答案2
得分: 0
我在阅读Jsoup的源代码后解决了我的问题,只需设置响应头部:
resp.Header.Set("Transfer-Encoding", "chunked")
resp.Header.Set("Content-Type", "application/json")
谢谢你们。
英文:
I have solved my problem after read Jsoup's source code, just set the response header
resp.Header.Set("Transfer-Encoding", "chunked")
resp.Header.Set("Content-Type", "application/json")
thanks you guys.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论