Repository: zeromicro/go-zero
Pull request #1840 (2022-04-28 05:50:17)

refactor: move json related header vars to internal


Patch:
diff --git a/core/stat/remotewriter.go b/core/stat/remotewriter.go
index b742e48d..e553bdd6 100644
--- a/core/stat/remotewriter.go
+++ b/core/stat/remotewriter.go
@@ -39,7 +39,7 @@ func (rw *RemoteWriter) Write(report *StatReport) error {
 	client := &http.Client{
 		Timeout: httpTimeout,
 	}
-	resp, err := client.Post(rw.endpoint, jsonContentType, bytes.NewBuffer(bs))
+	resp, err := client.Post(rw.endpoint, jsonContentType, bytes.NewReader(bs))
 	if err != nil {
 		return err
 	}
diff --git a/rest/httpc/requests.go b/rest/httpc/requests.go
index 06ca6a73..b6c9e861 100644
--- a/rest/httpc/requests.go
+++ b/rest/httpc/requests.go
@@ -13,6 +13,7 @@ import (
 	"github.com/zeromicro/go-zero/core/lang"
 	"github.com/zeromicro/go-zero/core/mapping"
 	"github.com/zeromicro/go-zero/rest/httpc/internal"
+	"github.com/zeromicro/go-zero/rest/internal/header"
 )
 
 var interceptors = []internal.Interceptor{
@@ -98,7 +99,7 @@ func buildRequest(ctx context.Context, method, url string, data interface{}) (*h
 	req.URL.RawQuery = buildFormQuery(u, val[formKey])
 	fillHeader(req, val[headerKey])
 	if hasJsonBody {
-		req.Header.Set(contentType, applicationJson)
+		req.Header.Set(header.ContentType, header.JsonContentType)
 	}
 
 	return req, nil
diff --git a/rest/httpc/responses.go b/rest/httpc/responses.go
index 7147ad64..560e1950 100644
--- a/rest/httpc/responses.go
+++ b/rest/httpc/responses.go
@@ -6,6 +6,7 @@ import (
 
 	"github.com/zeromicro/go-zero/core/mapping"
 	"github.com/zeromicro/go-zero/rest/internal/encoding"
+	"github.com/zeromicro/go-zero/rest/internal/header"
 )
 
 // Parse parses the response.
@@ -32,5 +33,5 @@ func ParseJsonBody(resp *http.Response, val interface{}) error {
 }
 
 func withJsonBody(r *http.Response) bool {
-	return r.ContentLength > 0 && strings.Contains(r.Header.Get(contentType), applicationJson)
+	return r.ContentLength > 0 && strings.Contains(r.Header.Get(header.ContentType), header.ApplicationJson)
 }
diff --git a/rest/httpc/vars.go b/rest/httpc/vars.go
index 5f318dd7..5bd5637b 100644
--- a/rest/httpc/vars.go
+++ b/rest/httpc/vars.go
@@ -3,14 +3,12 @@ package httpc
 import "errors"
 
 const (
-	pathKey         = "path"
-	formKey         = "form"
-	headerKey       = "header"
-	jsonKey         = "json"
-	slash           = "/"
-	colon           = ':'
-	contentType     = "Content-Type"
-	applicationJson = "application/json; charset=utf-8"
+	pathKey   = "path"
+	formKey   = "form"
+	headerKey = "header"
+	jsonKey   = "json"
+	slash     = "/"
+	colon     = ':'
 )
 
 // ErrGetWithBody indicates that GET request with body.
diff --git a/rest/httpx/requests.go b/rest/httpx/requests.go
index 4b3da146..f8fe7169 100644
--- a/rest/httpx/requests.go
+++ b/rest/httpx/requests.go
@@ -7,6 +7,7 @@ import (
 
 	"github.com/zeromicro/go-zero/core/mapping"
 	"github.com/zeromicro/go-zero/rest/internal/encoding"
+	"github.com/zeromicro/go-zero/rest/internal/header"
 	"github.com/zeromicro/go-zero/rest/pathvar"
 )
 
@@ -114,5 +115,5 @@ func ParsePath(r *http.Request, v interface{}) error {
 }
 
 func withJsonBody(r *http.Request) bool {
-	return r.ContentLength > 0 && strings.Contains(r.Header.Get(ContentType), ApplicationJson)
+	return r.ContentLength > 0 && strings.Contains(r.Header.Get(header.ContentType), header.ApplicationJson)
 }
diff --git a/rest/httpx/responses.go b/rest/httpx/responses.go
index 28b4ba1b..355de21a 100644
--- a/rest/httpx/responses.go
+++ b/rest/httpx/responses.go
@@ -6,6 +6,7 @@ import (
 	"sync"
 
 	"github.com/zeromicro/go-zero/core/logx"
+	"github.com/zeromicro/go-zero/rest/internal/header"
 )
 
 var (
@@ -67,7 +68,7 @@ func WriteJson(w http.ResponseWriter, code int, v interface{}) {
 		return
 	}
 
-	w.Header().Set(ContentType, ApplicationJson)
+	w.Header().Set(ContentType, header.JsonContentType)
 	w.WriteHeader(code)
 
 	if n, err := w.Write(bs); err != nil {
diff --git a/rest/httpx/vars.go b/rest/httpx/vars.go
index 1604727f..750bcd20 100644
--- a/rest/httpx/vars.go
+++ b/rest/httpx/vars.go
@@ -1,14 +1,16 @@
 package httpx
 
+import "github.com/zeromicro/go-zero/rest/internal/header"
+
 const (
-	// ApplicationJson means application/json.
-	ApplicationJson = "application/json; charset=utf-8"
 	// ContentEncoding means Content-Encoding.
 	ContentEncoding = "Content-Encoding"
 	// ContentSecurity means X-Content-Security.
 	ContentSecurity = "X-Content-Security"
 	// ContentType means Content-Type.
-	ContentType = "Content-Type"
+	ContentType = header.ContentType
+	// JsonContentType means application/json.
+	JsonContentType = header.JsonContentType
 	// KeyField means key.
 	KeyField = "key"
 	// SecretField means secret.
diff --git a/rest/internal/header/headers.go b/rest/internal/header/headers.go
new file mode 100644
index 00000000..29fd5e27
--- /dev/null
+++ b/rest/internal/header/headers.go
@@ -0,0 +1,10 @@
+package header
+
+const (
+	// ApplicationJson stands for application/json.
+	ApplicationJson = "application/json"
+	// ContentType is the header key for Content-Type.
+	ContentType = "Content-Type"
+	// JsonContentType is the content type for JSON.
+	JsonContentType = "application/json; charset=utf-8"
+)
diff --git a/tools/goctl/api/dartgen/vars.go b/tools/goctl/api/dartgen/vars.go
index 68cbaa82..b1a98c6d 100644
--- a/tools/goctl/api/dartgen/vars.go
+++ b/tools/goctl/api/dartgen/vars.go
@@ -149,7 +149,7 @@ Future _apiRequest(String method, String path, dynamic data,
 				r = await client.getUrl(Uri.parse('https://' + serverHost + path));
 			}
 
-			r.headers.set('Content-Type', 'application/json');
+			r.headers.set('Content-Type', 'application/json; charset=utf-8');
 			if (tokens != null) {
 				r.headers.set('Authorization', tokens.accessToken);
 			}


Test patch:
diff --git a/rest/httpc/requests_test.go b/rest/httpc/requests_test.go
index a2b4bfd1..551f058c 100644
--- a/rest/httpc/requests_test.go
+++ b/rest/httpc/requests_test.go
@@ -8,6 +8,7 @@ import (
 
 	"github.com/stretchr/testify/assert"
 	"github.com/zeromicro/go-zero/rest/httpx"
+	"github.com/zeromicro/go-zero/rest/internal/header"
 	"github.com/zeromicro/go-zero/rest/router"
 )
 
@@ -27,7 +28,7 @@ func TestDoRequest_NotFound(t *testing.T) {
 	defer svr.Close()
 	req, err := http.NewRequest(http.MethodPost, svr.URL, nil)
 	assert.Nil(t, err)
-	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set(header.ContentType, header.JsonContentType)
 	resp, err := DoRequest(req)
 	assert.Nil(t, err)
 	assert.Equal(t, http.StatusNotFound, resp.StatusCode)
diff --git a/rest/httpc/responses_test.go b/rest/httpc/responses_test.go
index aed53c9f..b273325e 100644
--- a/rest/httpc/responses_test.go
+++ b/rest/httpc/responses_test.go
@@ -6,6 +6,7 @@ import (
 	"testing"
 
 	"github.com/stretchr/testify/assert"
+	"github.com/zeromicro/go-zero/rest/internal/header"
 )
 
 func TestParse(t *testing.T) {
@@ -16,7 +17,7 @@ func TestParse(t *testing.T) {
 	}
 	svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		w.Header().Set("foo", "bar")
-		w.Header().Set(contentType, applicationJson)
+		w.Header().Set(header.ContentType, header.JsonContentType)
 		w.Write([]byte(`{"name":"kevin","value":100}`))
 	}))
 	defer svr.Close()
@@ -36,7 +37,7 @@ func TestParseHeaderError(t *testing.T) {
 	}
 	svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		w.Header().Set("foo", "bar")
-		w.Header().Set(contentType, applicationJson)
+		w.Header().Set(header.ContentType, header.JsonContentType)
 	}))
 	defer svr.Close()
 	req, err := http.NewRequest(http.MethodGet, svr.URL, nil)
@@ -52,7 +53,7 @@ func TestParseNoBody(t *testing.T) {
 	}
 	svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		w.Header().Set("foo", "bar")
-		w.Header().Set(contentType, applicationJson)
+		w.Header().Set(header.ContentType, header.JsonContentType)
 	}))
 	defer svr.Close()
 	req, err := http.NewRequest(http.MethodGet, svr.URL, nil)
diff --git a/rest/httpc/service_test.go b/rest/httpc/service_test.go
index 0af1c6ee..f4a32efd 100644
--- a/rest/httpc/service_test.go
+++ b/rest/httpc/service_test.go
@@ -7,6 +7,7 @@ import (
 	"testing"
 
 	"github.com/stretchr/testify/assert"
+	"github.com/zeromicro/go-zero/rest/internal/header"
 )
 
 func TestNamedService_DoRequest(t *testing.T) {
@@ -43,7 +44,7 @@ func TestNamedService_DoRequestPost(t *testing.T) {
 	service := NewService("foo")
 	req, err := http.NewRequest(http.MethodPost, svr.URL, nil)
 	assert.Nil(t, err)
-	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set(header.ContentType, header.JsonContentType)
 	resp, err := service.DoRequest(req)
 	assert.Nil(t, err)
 	assert.Equal(t, http.StatusNotFound, resp.StatusCode)
diff --git a/rest/httpx/requests_test.go b/rest/httpx/requests_test.go
index 63976d7e..e0d1ffee 100644
--- a/rest/httpx/requests_test.go
+++ b/rest/httpx/requests_test.go
@@ -8,6 +8,7 @@ import (
 	"testing"
 
 	"github.com/stretchr/testify/assert"
+	"github.com/zeromicro/go-zero/rest/internal/header"
 	"github.com/zeromicro/go-zero/rest/pathvar"
 )
 
@@ -204,7 +205,7 @@ func TestParseJsonBody(t *testing.T) {
 
 		body := `{"name":"kevin", "age": 18}`
 		r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body))
-		r.Header.Set(ContentType, ApplicationJson)
+		r.Header.Set(ContentType, header.JsonContentType)
 
 		assert.Nil(t, Parse(r, &v))
 		assert.Equal(t, "kevin", v.Name)
@@ -267,7 +268,7 @@ func TestParseHeaders(t *testing.T) {
 	request.Header.Add("addrs", "addr2")
 	request.Header.Add("X-Forwarded-For", "10.0.10.11")
 	request.Header.Add("x-real-ip", "10.0.11.10")
-	request.Header.Add("Accept", "application/json")
+	request.Header.Add("Accept", header.JsonContentType)
 	err = ParseHeaders(request, &v)
 	if err != nil {
 		t.Fatal(err)
@@ -277,7 +278,7 @@ func TestParseHeaders(t *testing.T) {
 	assert.Equal(t, []string{"addr1", "addr2"}, v.Addrs)
 	assert.Equal(t, "10.0.10.11", v.XForwardedFor)
 	assert.Equal(t, "10.0.11.10", v.XRealIP)
-	assert.Equal(t, "application/json", v.Accept)
+	assert.Equal(t, header.JsonContentType, v.Accept)
 }
 
 func TestParseHeaders_Error(t *testing.T) {
diff --git a/rest/router/patrouter_test.go b/rest/router/patrouter_test.go
index 1425a206..a88dfe3d 100644
--- a/rest/router/patrouter_test.go
+++ b/rest/router/patrouter_test.go
@@ -11,13 +11,11 @@ import (
 
 	"github.com/stretchr/testify/assert"
 	"github.com/zeromicro/go-zero/rest/httpx"
+	"github.com/zeromicro/go-zero/rest/internal/header"
 	"github.com/zeromicro/go-zero/rest/pathvar"
 )
 
-const (
-	applicationJsonWithUtf8 = "application/json; charset=utf-8"
-	contentLength           = "Content-Length"
-)
+const contentLength = "Content-Length"
 
 type mockedResponseWriter struct {
 	code int
@@ -167,7 +165,7 @@ func TestParseJsonPost(t *testing.T) {
 	r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017?nickname=whatever&zipcode=200000",
 		bytes.NewBufferString(`{"location": "shanghai", "time": 20170912}`))
 	assert.Nil(t, err)
-	r.Header.Set(httpx.ContentType, httpx.ApplicationJson)
+	r.Header.Set(httpx.ContentType, httpx.JsonContentType)
 
 	router := NewRouter()
 	err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc(func(
@@ -199,7 +197,7 @@ func TestParseJsonPostWithIntSlice(t *testing.T) {
 	r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017",
 		bytes.NewBufferString(`{"ages": [1, 2], "years": [3, 4]}`))
 	assert.Nil(t, err)
-	r.Header.Set(httpx.ContentType, httpx.ApplicationJson)
+	r.Header.Set(httpx.ContentType, httpx.JsonContentType)
 
 	router := NewRouter()
 	err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc(func(
@@ -227,7 +225,7 @@ func TestParseJsonPostError(t *testing.T) {
 	r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017?nickname=whatever&zipcode=200000",
 		bytes.NewBufferString(payload))
 	assert.Nil(t, err)
-	r.Header.Set(httpx.ContentType, httpx.ApplicationJson)
+	r.Header.Set(httpx.ContentType, httpx.JsonContentType)
 
 	router := NewRouter()
 	err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc(
@@ -255,7 +253,7 @@ func TestParseJsonPostInvalidRequest(t *testing.T) {
 	r, err := http.NewRequest(http.MethodPost, "http://hello.com/",
 		bytes.NewBufferString(payload))
 	assert.Nil(t, err)
-	r.Header.Set(httpx.ContentType, httpx.ApplicationJson)
+	r.Header.Set(httpx.ContentType, httpx.JsonContentType)
 
 	router := NewRouter()
 	err = router.Handle(http.MethodPost, "/", http.HandlerFunc(
@@ -277,7 +275,7 @@ func TestParseJsonPostRequired(t *testing.T) {
 	r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017",
 		bytes.NewBufferString(`{"location": "shanghai"`))
 	assert.Nil(t, err)
-	r.Header.Set(httpx.ContentType, httpx.ApplicationJson)
+	r.Header.Set(httpx.ContentType, httpx.JsonContentType)
 
 	router := NewRouter()
 	err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc(
@@ -455,7 +453,7 @@ func TestParsePtrInRequest(t *testing.T) {
 	r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017",
 		bytes.NewBufferString(`{"audio": {"volume": 100}}`))
 	assert.Nil(t, err)
-	r.Header.Set(httpx.ContentType, httpx.ApplicationJson)
+	r.Header.Set(httpx.ContentType, httpx.JsonContentType)
 
 	type (
 		Request struct {
@@ -603,7 +601,7 @@ func TestParseWrappedRequest(t *testing.T) {
 func TestParseWrappedGetRequestWithJsonHeader(t *testing.T) {
 	r, err := http.NewRequest(http.MethodGet, "http://hello.com/kevin/2017", nil)
 	assert.Nil(t, err)
-	r.Header.Set(httpx.ContentType, applicationJsonWithUtf8)
+	r.Header.Set(httpx.ContentType, header.JsonContentType)
 
 	type (
 		Request struct {
@@ -636,7 +634,7 @@ func TestParseWrappedGetRequestWithJsonHeader(t *testing.T) {
 func TestParseWrappedHeadRequestWithJsonHeader(t *testing.T) {
 	r, err := http.NewRequest(http.MethodHead, "http://hello.com/kevin/2017", nil)
 	assert.Nil(t, err)
-	r.Header.Set(httpx.ContentType, applicationJsonWithUtf8)
+	r.Header.Set(httpx.ContentType, header.JsonContentType)
 
 	type (
 		Request struct {
@@ -702,7 +700,7 @@ func TestParseWithAll(t *testing.T) {
 	r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017?nickname=whatever&zipcode=200000",
 		bytes.NewBufferString(`{"location": "shanghai", "time": 20170912}`))
 	assert.Nil(t, err)
-	r.Header.Set(httpx.ContentType, httpx.ApplicationJson)
+	r.Header.Set(httpx.ContentType, httpx.JsonContentType)
 
 	router := NewRouter()
 	err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -733,7 +731,7 @@ func TestParseWithAllUtf8(t *testing.T) {
 	r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017?nickname=whatever&zipcode=200000",
 		bytes.NewBufferString(`{"location": "shanghai", "time": 20170912}`))
 	assert.Nil(t, err)
-	r.Header.Set(httpx.ContentType, applicationJsonWithUtf8)
+	r.Header.Set(httpx.ContentType, header.JsonContentType)
 
 	router := NewRouter()
 	err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc(
@@ -923,7 +921,7 @@ func TestParseWithMissingAllPaths(t *testing.T) {
 func TestParseGetWithContentLengthHeader(t *testing.T) {
 	r, err := http.NewRequest(http.MethodGet, "http://hello.com/kevin/2017?nickname=whatever&zipcode=200000", nil)
 	assert.Nil(t, err)
-	r.Header.Set(httpx.ContentType, httpx.ApplicationJson)
+	r.Header.Set(httpx.ContentType, header.JsonContentType)
 	r.Header.Set(contentLength, "1024")
 
 	router := NewRouter()
@@ -951,7 +949,7 @@ func TestParseJsonPostWithTypeMismatch(t *testing.T) {
 	r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017?nickname=whatever&zipcode=200000",
 		bytes.NewBufferString(`{"time": "20170912"}`))
 	assert.Nil(t, err)
-	r.Header.Set(httpx.ContentType, applicationJsonWithUtf8)
+	r.Header.Set(httpx.ContentType, header.JsonContentType)
 
 	router := NewRouter()
 	err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc(
@@ -977,7 +975,7 @@ func TestParseJsonPostWithInt2String(t *testing.T) {
 	r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017",
 		bytes.NewBufferString(`{"time": 20170912}`))
 	assert.Nil(t, err)
-	r.Header.Set(httpx.ContentType, applicationJsonWithUtf8)
+	r.Header.Set(httpx.ContentType, header.JsonContentType)
 
 	router := NewRouter()
 	err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc(