当在Golang中使用头文件时,会打印两个结果。

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

Two results are printed when headers are used in golang

问题

这是我正在使用的代码:

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", TestFunc)
	http.ListenAndServe(":8080", nil)
}

func TestFunc(w http.ResponseWriter, r *http.Request) {
	fmt.Println("test")

	// --------------------- headers ------------------------
	w.Header().Set("Accept-Charset", "utf-8")
	w.Header().Set("Accept-Encoding", "gzip")
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(http.StatusOK)
}

上面的代码可以正常工作,并且每次都会打印两个结果(test test)。

当我移除了头部信息后,代码可以正常工作,并且只返回 "test"。

这段代码有什么问题?

英文:

This is the code I'm working with:

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", TestFunc)
	http.ListenAndServe(":8080", nil)
}

func TestFunc(w http.ResponseWriter, r *http.Request) {
	fmt.Println("test")

	// --------------------- headers ------------------------
	w.Header().Set("Accept-Charset", "utf-8")
	w.Header().Set("Accept-Encoding", "gzip")
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(http.StatusOK)
}

The code above works and prints two result (test test) every time.

When I remove the headers, code works fine and returns only "test".

What is the issue in this code?

答案1

得分: 2

您的浏览器可能正在请求/favicon.ico。在请求处理程序中打印出r.URL的值将确认这一点。

英文:

Your browser is likely requesting /favicon.ico. Printing out the value of r.URL in the request handler will confirm this.

huangapple
  • 本文由 发表于 2017年8月28日 19:49:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/45918273.html
匿名

发表评论

匿名网友

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

确定