我正在尝试这个 Go 代码
package main
import (
"github.com/gorilla/mux"
"io"
"log"
"net/http"
)
func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"alive": true}`)
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/health", HealthCheckHandler).Methods("GET")
log.Printf("running server ...")
log.Fatal(http.ListenAndServe(":8000", router))
}
通过这个测试
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestHealthCheckHandler(t *testing.T) {
req, err := http.NewRequest("GET", "/health", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(HealthCheckHandler)
handler.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
t.Logf("%v", rr.Header())
if ctype := rr.Header().Get("Content-Type"); ctype != "application/json" {
t.Errorf("content type header does not match: got %v want %v",
ctype, "application/json")
}
}
当我运行测试时,一切正常
go test -v
=== RUN TestHealthCheckHandler
--- PASS: TestHealthCheckHandler (0.00s)
handlers_test.go:24: map[Content-Type:[application/json]]
PASS
ok 0.012s
是,但是当我运行该服务并用 curl 调用它时Content-Type,是application/jsonContent-Typetext/plain
curl -v localhost:8000/health
* Trying ::1...
* Connected to localhost (::1) port 8000 (#0)
> GET /health HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Thu, 14 Feb 2019 01:37:15 GMT
< Content-Length: 15
< Content-Type: text/plain; charset=utf-8
<
* Connection #0 to host localhost left intact
为什么行为不同于测试和执行?
MMMHUHU
婷婷同学_
相关分类