Skip to content

Commit

Permalink
refactor: move json related header vars to internal (#1840)
Browse files Browse the repository at this point in the history
* refactor: move json related header vars to internal

* refactor: use header.ContentType
  • Loading branch information
kevwan committed Apr 28, 2022
1 parent cef83ef commit 3bbc90e
Show file tree
Hide file tree
Showing 14 changed files with 58 additions and 42 deletions.
2 changes: 1 addition & 1 deletion core/stat/remotewriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
3 changes: 2 additions & 1 deletion rest/httpc/requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion rest/httpc/requests_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand All @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion rest/httpc/responses.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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)
}
7 changes: 4 additions & 3 deletions rest/httpc/responses_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/rest/internal/header"
)

func TestParse(t *testing.T) {
Expand All @@ -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()
Expand All @@ -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)
Expand All @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion rest/httpc/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
Expand Down
14 changes: 6 additions & 8 deletions rest/httpc/vars.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion rest/httpx/requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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)
}
7 changes: 4 additions & 3 deletions rest/httpx/requests_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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) {
Expand Down
3 changes: 2 additions & 1 deletion rest/httpx/responses.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"sync"

"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/internal/header"
)

var (
Expand Down Expand Up @@ -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 {
Expand Down
8 changes: 5 additions & 3 deletions rest/httpx/vars.go
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
10 changes: 10 additions & 0 deletions rest/internal/header/headers.go
Original file line number Diff line number Diff line change
@@ -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"
)
32 changes: 15 additions & 17 deletions rest/router/patrouter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand All @@ -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(
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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(
Expand All @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion tools/goctl/api/dartgen/vars.go
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down

0 comments on commit 3bbc90e

Please sign in to comment.