1
1
mirror of https://github.com/go-gitea/gitea synced 2025-07-22 18:28:37 +00:00

Add an abstract json layout to make it's easier to change json library (#16528)

* Add an abstract json layout to make it's easier to change json library

* Fix import

* Fix import sequence

* Fix blank lines

* Fix blank lines
This commit is contained in:
Lunny Xiao
2021-07-25 00:03:58 +08:00
committed by GitHub
parent e0f9635c06
commit 9f31f3aa8a
93 changed files with 272 additions and 264 deletions

View File

@@ -9,9 +9,10 @@ import (
"sync"
"time"
"code.gitea.io/gitea/modules/json"
mc "gitea.com/go-chi/cache"
lru "github.com/hashicorp/golang-lru"
jsoniter "github.com/json-iterator/go"
)
// TwoQueueCache represents a LRU 2Q cache adapter implementation
@@ -177,7 +178,6 @@ func (c *TwoQueueCache) StartAndGC(opts mc.Options) error {
size, err = strconv.Atoi(opts.AdapterConfig)
}
if err != nil {
json := jsoniter.ConfigCompatibleWithStandardLibrary
if !json.Valid([]byte(opts.AdapterConfig)) {
return err
}

View File

@@ -23,6 +23,7 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base"
mc "code.gitea.io/gitea/modules/cache"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/templates"
@@ -34,7 +35,6 @@ import (
"gitea.com/go-chi/cache"
"gitea.com/go-chi/session"
"github.com/go-chi/chi"
jsoniter "github.com/json-iterator/go"
"github.com/unknwon/com"
"github.com/unknwon/i18n"
"github.com/unrolled/render"
@@ -408,7 +408,6 @@ func (ctx *Context) Error(status int, contents ...string) {
func (ctx *Context) JSON(status int, content interface{}) {
ctx.Resp.Header().Set("Content-Type", "application/json;charset=utf-8")
ctx.Resp.WriteHeader(status)
json := jsoniter.ConfigCompatibleWithStandardLibrary
if err := json.NewEncoder(ctx.Resp).Encode(content); err != nil {
ctx.ServerError("Render JSON failed", err)
}

View File

@@ -11,7 +11,7 @@ import (
"strings"
"time"
jsoniter "github.com/json-iterator/go"
"code.gitea.io/gitea/modules/json"
)
func wrapNewlines(w io.Writer, prefix []byte, value []byte) (sum int64, err error) {
@@ -80,7 +80,6 @@ func (e *Event) WriteTo(w io.Writer) (int64, error) {
data = []byte(v)
default:
var err error
json := jsoniter.ConfigCompatibleWithStandardLibrary
data, err = json.Marshal(e.Data)
if err != nil {
return sum, err
@@ -91,7 +90,6 @@ func (e *Event) WriteTo(w io.Writer) (int64, error) {
if err != nil {
return sum, err
}
}
n, err = wrapNewlines(w, []byte("id: "), []byte(e.ID))

View File

@@ -24,7 +24,7 @@ import (
"sync"
"time"
jsoniter "github.com/json-iterator/go"
"code.gitea.io/gitea/modules/json"
)
var defaultSetting = Settings{false, "GiteaServer", 60 * time.Second, 60 * time.Second, nil, nil, nil, false}
@@ -443,7 +443,6 @@ func (r *Request) ToJSON(v interface{}) error {
if err != nil {
return err
}
json := jsoniter.ConfigCompatibleWithStandardLibrary
err = json.Unmarshal(data, v)
return err
}

View File

@@ -18,13 +18,13 @@ import (
"code.gitea.io/gitea/modules/analyze"
"code.gitea.io/gitea/modules/charset"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/typesniffer"
"github.com/go-enry/go-enry/v2"
jsoniter "github.com/json-iterator/go"
"github.com/olivere/elastic/v7"
)
@@ -321,7 +321,6 @@ func convertResult(searchResult *elastic.SearchResult, kw string, pageSize int)
repoID, fileName := parseIndexerID(hit.Id)
var res = make(map[string]interface{})
json := jsoniter.ConfigCompatibleWithStandardLibrary
if err := json.Unmarshal(hit.Source, &res); err != nil {
return 0, nil, nil, err
}

142
modules/json/json.go Normal file
View File

@@ -0,0 +1,142 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package json
import (
"bytes"
"encoding/json"
"io"
jsoniter "github.com/json-iterator/go"
)
// Encoder represents an encoder for json
type Encoder interface {
Encode(v interface{}) error
}
// Decoder represents a decoder for json
type Decoder interface {
Decode(v interface{}) error
}
// Interface represents an interface to handle json data
type Interface interface {
Marshal(v interface{}) ([]byte, error)
Unmarshal(data []byte, v interface{}) error
NewEncoder(writer io.Writer) Encoder
NewDecoder(reader io.Reader) Decoder
Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error
}
var (
// DefaultJSONHandler default json handler
DefaultJSONHandler Interface = JSONiter{jsoniter.ConfigCompatibleWithStandardLibrary}
_ Interface = StdJSON{}
_ Interface = JSONiter{}
)
// StdJSON implements Interface via encoding/json
type StdJSON struct{}
// Marshal implements Interface
func (StdJSON) Marshal(v interface{}) ([]byte, error) {
return json.Marshal(v)
}
// Unmarshal implements Interface
func (StdJSON) Unmarshal(data []byte, v interface{}) error {
return json.Unmarshal(data, v)
}
// NewEncoder implements Interface
func (StdJSON) NewEncoder(writer io.Writer) Encoder {
return json.NewEncoder(writer)
}
// NewDecoder implements Interface
func (StdJSON) NewDecoder(reader io.Reader) Decoder {
return json.NewDecoder(reader)
}
// Indent implements Interface
func (StdJSON) Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error {
return json.Indent(dst, src, prefix, indent)
}
// JSONiter implements Interface via jsoniter
type JSONiter struct {
jsoniter.API
}
// Marshal implements Interface
func (j JSONiter) Marshal(v interface{}) ([]byte, error) {
return j.API.Marshal(v)
}
// Unmarshal implements Interface
func (j JSONiter) Unmarshal(data []byte, v interface{}) error {
return j.API.Unmarshal(data, v)
}
// NewEncoder implements Interface
func (j JSONiter) NewEncoder(writer io.Writer) Encoder {
return j.API.NewEncoder(writer)
}
// NewDecoder implements Interface
func (j JSONiter) NewDecoder(reader io.Reader) Decoder {
return j.API.NewDecoder(reader)
}
// Indent implements Interface, since jsoniter don't support Indent, just use encoding/json's
func (j JSONiter) Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error {
return json.Indent(dst, src, prefix, indent)
}
// Marshal converts object as bytes
func Marshal(v interface{}) ([]byte, error) {
return DefaultJSONHandler.Marshal(v)
}
// Unmarshal decodes object from bytes
func Unmarshal(data []byte, v interface{}) error {
return DefaultJSONHandler.Unmarshal(data, v)
}
// NewEncoder creates an encoder to write objects to writer
func NewEncoder(writer io.Writer) Encoder {
return DefaultJSONHandler.NewEncoder(writer)
}
// NewDecoder creates a decoder to read objects from reader
func NewDecoder(reader io.Reader) Decoder {
return DefaultJSONHandler.NewDecoder(reader)
}
// Indent appends to dst an indented form of the JSON-encoded src.
func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error {
return DefaultJSONHandler.Indent(dst, src, prefix, indent)
}
// MarshalIndent copied from encoding/json
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
b, err := Marshal(v)
if err != nil {
return nil, err
}
var buf bytes.Buffer
err = Indent(&buf, b, prefix, indent)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Valid proxy to json.Valid
func Valid(data []byte) bool {
return json.Valid(data)
}

View File

@@ -13,9 +13,8 @@ import (
"net/url"
"strings"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
jsoniter "github.com/json-iterator/go"
)
const batchSize = 20
@@ -69,7 +68,7 @@ func (c *HTTPClient) batch(ctx context.Context, operation string, objects []Poin
request := &BatchRequest{operation, c.transferNames(), nil, objects}
payload := new(bytes.Buffer)
err := jsoniter.NewEncoder(payload).Encode(request)
err := json.NewEncoder(payload).Encode(request)
if err != nil {
log.Error("Error encoding json: %v", err)
return nil, err
@@ -102,7 +101,7 @@ func (c *HTTPClient) batch(ctx context.Context, operation string, objects []Poin
}
var response BatchResponse
err = jsoniter.NewDecoder(res.Body).Decode(&response)
err = json.NewDecoder(res.Body).Decode(&response)
if err != nil {
log.Error("Error decoding json: %v", err)
return nil, err

View File

@@ -13,7 +13,8 @@ import (
"strings"
"testing"
jsoniter "github.com/json-iterator/go"
"code.gitea.io/gitea/modules/json"
"github.com/stretchr/testify/assert"
)
@@ -146,7 +147,7 @@ func lfsTestRoundtripHandler(req *http.Request) *http.Response {
}
payload := new(bytes.Buffer)
jsoniter.NewEncoder(payload).Encode(batchResponse)
json.NewEncoder(payload).Encode(batchResponse)
return &http.Response{StatusCode: http.StatusOK, Body: ioutil.NopCloser(payload)}
}
@@ -160,7 +161,7 @@ func TestHTTPClientDownload(t *testing.T) {
assert.Equal(t, MediaType, req.Header.Get("Accept"))
var batchRequest BatchRequest
err := jsoniter.NewDecoder(req.Body).Decode(&batchRequest)
err := json.NewDecoder(req.Body).Decode(&batchRequest)
assert.NoError(t, err)
assert.Equal(t, "download", batchRequest.Operation)
@@ -267,7 +268,7 @@ func TestHTTPClientUpload(t *testing.T) {
assert.Equal(t, MediaType, req.Header.Get("Accept"))
var batchRequest BatchRequest
err := jsoniter.NewDecoder(req.Body).Decode(&batchRequest)
err := json.NewDecoder(req.Body).Decode(&batchRequest)
assert.NoError(t, err)
assert.Equal(t, "upload", batchRequest.Operation)

View File

@@ -12,9 +12,8 @@ import (
"io"
"net/http"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
jsoniter "github.com/json-iterator/go"
)
// TransferAdapter represents an adapter for downloading/uploading LFS objects
@@ -65,7 +64,7 @@ func (a *BasicTransferAdapter) Upload(ctx context.Context, l *Link, p Pointer, r
// Verify calls the verify handler on the LFS server
func (a *BasicTransferAdapter) Verify(ctx context.Context, l *Link, p Pointer) error {
b, err := jsoniter.Marshal(p)
b, err := json.Marshal(p)
if err != nil {
log.Error("Error encoding json: %v", err)
return err
@@ -128,7 +127,7 @@ func handleErrorResponse(resp *http.Response) error {
func decodeReponseError(r io.Reader) (ErrorResponse, error) {
var er ErrorResponse
err := jsoniter.NewDecoder(r).Decode(&er)
err := json.NewDecoder(r).Decode(&er)
if err != nil {
log.Error("Error decoding json: %v", err)
}

View File

@@ -13,7 +13,8 @@ import (
"strings"
"testing"
jsoniter "github.com/json-iterator/go"
"code.gitea.io/gitea/modules/json"
"github.com/stretchr/testify/assert"
)
@@ -49,7 +50,7 @@ func TestBasicTransferAdapter(t *testing.T) {
assert.Equal(t, MediaType, req.Header.Get("Content-Type"))
var vp Pointer
err := jsoniter.NewDecoder(req.Body).Decode(&vp)
err := json.NewDecoder(req.Body).Decode(&vp)
assert.NoError(t, err)
assert.Equal(t, p.Oid, vp.Oid)
assert.Equal(t, p.Size, vp.Size)
@@ -60,7 +61,7 @@ func TestBasicTransferAdapter(t *testing.T) {
Message: "Object not found",
}
payload := new(bytes.Buffer)
jsoniter.NewEncoder(payload).Encode(er)
json.NewEncoder(payload).Encode(er)
return &http.Response{StatusCode: http.StatusNotFound, Body: ioutil.NopCloser(payload)}
} else {

View File

@@ -10,7 +10,7 @@ import (
"io"
"net"
jsoniter "github.com/json-iterator/go"
"code.gitea.io/gitea/modules/json"
)
type connWriter struct {
@@ -106,7 +106,6 @@ func NewConn() LoggerProvider {
// Init inits connection writer with json config.
// json config only need key "level".
func (log *ConnLogger) Init(jsonconfig string) error {
json := jsoniter.ConfigCompatibleWithStandardLibrary
err := json.Unmarshal([]byte(jsonconfig), log)
if err != nil {
return fmt.Errorf("Unable to parse JSON: %v", err)

View File

@@ -10,7 +10,7 @@ import (
"io"
"os"
jsoniter "github.com/json-iterator/go"
"code.gitea.io/gitea/modules/json"
)
// CanColorStdout reports if we can color the Stdout
@@ -52,7 +52,6 @@ func NewConsoleLogger() LoggerProvider {
// Init inits connection writer with json config.
// json config only need key "level".
func (log *ConsoleLogger) Init(config string) error {
json := jsoniter.ConfigCompatibleWithStandardLibrary
err := json.Unmarshal([]byte(config), log)
if err != nil {
return fmt.Errorf("Unable to parse JSON: %v", err)

View File

@@ -15,8 +15,8 @@ import (
"sync"
"time"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/util"
jsoniter "github.com/json-iterator/go"
)
// FileLogger implements LoggerProvider.
@@ -101,7 +101,6 @@ func NewFileLogger() LoggerProvider {
// "rotate":true
// }
func (log *FileLogger) Init(config string) error {
json := jsoniter.ConfigCompatibleWithStandardLibrary
if err := json.Unmarshal([]byte(config), log); err != nil {
return fmt.Errorf("Unable to parse JSON: %v", err)
}

View File

@@ -10,7 +10,7 @@ import (
"os"
"strings"
jsoniter "github.com/json-iterator/go"
"code.gitea.io/gitea/modules/json"
)
// Level is the level of the logger
@@ -104,7 +104,6 @@ func FromString(level string) Level {
// UnmarshalJSON takes text and turns it into a Level
func (l *Level) UnmarshalJSON(b []byte) error {
var tmp interface{}
json := jsoniter.ConfigCompatibleWithStandardLibrary
err := json.Unmarshal(b, &tmp)
if err != nil {
fmt.Fprintf(os.Stderr, "Err: %v", err)

View File

@@ -8,7 +8,8 @@ import (
"fmt"
"testing"
jsoniter "github.com/json-iterator/go"
"code.gitea.io/gitea/modules/json"
"github.com/stretchr/testify/assert"
)
@@ -17,7 +18,6 @@ type testLevel struct {
}
func TestLevelMarshalUnmarshalJSON(t *testing.T) {
json := jsoniter.ConfigCompatibleWithStandardLibrary
levelBytes, err := json.Marshal(testLevel{
Level: INFO,
})

View File

@@ -10,7 +10,7 @@ import (
"net/smtp"
"strings"
jsoniter "github.com/json-iterator/go"
"code.gitea.io/gitea/modules/json"
)
type smtpWriter struct {
@@ -57,7 +57,6 @@ func NewSMTPLogger() LoggerProvider {
// "level":LevelError
// }
func (log *SMTPLogger) Init(jsonconfig string) error {
json := jsoniter.ConfigCompatibleWithStandardLibrary
err := json.Unmarshal([]byte(jsonconfig), log)
if err != nil {
return fmt.Errorf("Unable to parse JSON: %v", err)

View File

@@ -10,10 +10,10 @@ import (
"strings"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/notification/base"
"code.gitea.io/gitea/modules/repository"
jsoniter "github.com/json-iterator/go"
)
type actionNotifier struct {
@@ -296,7 +296,6 @@ func (*actionNotifier) NotifyPullRevieweDismiss(doer *models.User, review *model
}
func (a *actionNotifier) NotifyPushCommits(pusher *models.User, repo *models.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) {
json := jsoniter.ConfigCompatibleWithStandardLibrary
data, err := json.Marshal(commits)
if err != nil {
log.Error("Marshal: %v", err)
@@ -368,7 +367,6 @@ func (a *actionNotifier) NotifyDeleteRef(doer *models.User, repo *models.Reposit
}
func (a *actionNotifier) NotifySyncPushCommits(pusher *models.User, repo *models.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) {
json := jsoniter.ConfigCompatibleWithStandardLibrary
data, err := json.Marshal(commits)
if err != nil {
log.Error("json.Marshal: %v", err)

View File

@@ -6,15 +6,14 @@ package private
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"time"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/setting"
jsoniter "github.com/json-iterator/go"
)
// Git environment variables
@@ -88,7 +87,6 @@ func HookPreReceive(ctx context.Context, ownerName, repoName string, opts HookOp
)
req := newInternalRequest(ctx, reqURL, "POST")
req = req.Header("Content-Type", "application/json")
json := jsoniter.ConfigCompatibleWithStandardLibrary
jsonBytes, _ := json.Marshal(opts)
req.Body(jsonBytes)
req.SetTimeout(60*time.Second, time.Duration(60+len(opts.OldCommitIDs))*time.Second)
@@ -115,7 +113,6 @@ func HookPostReceive(ctx context.Context, ownerName, repoName string, opts HookO
req := newInternalRequest(ctx, reqURL, "POST")
req = req.Header("Content-Type", "application/json")
req.SetTimeout(60*time.Second, time.Duration(60+len(opts.OldCommitIDs))*time.Second)
json := jsoniter.ConfigCompatibleWithStandardLibrary
jsonBytes, _ := json.Marshal(opts)
req.Body(jsonBytes)
resp, err := req.Response()

View File

@@ -12,8 +12,8 @@ import (
"net/http"
"code.gitea.io/gitea/modules/httplib"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/setting"
jsoniter "github.com/json-iterator/go"
)
func newRequest(ctx context.Context, url, method string) *httplib.Request {
@@ -30,7 +30,6 @@ type Response struct {
func decodeJSONError(resp *http.Response) *Response {
var res Response
json := jsoniter.ConfigCompatibleWithStandardLibrary
err := json.NewDecoder(resp.Body).Decode(&res)
if err != nil {
res.Err = err.Error()

View File

@@ -10,8 +10,8 @@ import (
"io/ioutil"
"net/http"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/setting"
jsoniter "github.com/json-iterator/go"
)
// Email structure holds a data for sending general emails
@@ -33,7 +33,6 @@ func SendEmail(ctx context.Context, subject, message string, to []string) (int,
req := newInternalRequest(ctx, reqURL, "POST")
req = req.Header("Content-Type", "application/json")
json := jsoniter.ConfigCompatibleWithStandardLibrary
jsonBytes, _ := json.Marshal(Email{
Subject: subject,
Message: message,

View File

@@ -11,8 +11,8 @@ import (
"net/url"
"time"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/setting"
jsoniter "github.com/json-iterator/go"
)
// Shutdown calls the internal shutdown function
@@ -66,7 +66,6 @@ func FlushQueues(ctx context.Context, timeout time.Duration, nonBlocking bool) (
req.SetTimeout(timeout+10*time.Second, timeout+10*time.Second)
}
req = req.Header("Content-Type", "application/json")
json := jsoniter.ConfigCompatibleWithStandardLibrary
jsonBytes, _ := json.Marshal(FlushOptions{
Timeout: timeout,
NonBlocking: nonBlocking,
@@ -153,7 +152,6 @@ func AddLogger(ctx context.Context, group, name, mode string, config map[string]
req := newInternalRequest(ctx, reqURL, "POST")
req = req.Header("Content-Type", "application/json")
json := jsoniter.ConfigCompatibleWithStandardLibrary
jsonBytes, _ := json.Marshal(LoggerOptions{
Group: group,
Name: name,

View File

@@ -11,8 +11,8 @@ import (
"net/http"
"time"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/setting"
jsoniter "github.com/json-iterator/go"
)
// RestoreParams structure holds a data for restore repository
@@ -30,7 +30,6 @@ func RestoreRepo(ctx context.Context, repoDir, ownerName, repoName string, units
req := newInternalRequest(ctx, reqURL, "POST")
req.SetTimeout(3*time.Second, 0) // since the request will spend much time, don't timeout
req = req.Header("Content-Type", "application/json")
json := jsoniter.ConfigCompatibleWithStandardLibrary
jsonBytes, _ := json.Marshal(RestoreParams{
RepoDir: repoDir,
OwnerName: ownerName,

View File

@@ -11,8 +11,8 @@ import (
"net/url"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/setting"
jsoniter "github.com/json-iterator/go"
)
// KeyAndOwner is the response from ServNoCommand
@@ -35,7 +35,6 @@ func ServNoCommand(ctx context.Context, keyID int64) (*models.PublicKey, *models
}
var keyAndOwner KeyAndOwner
json := jsoniter.ConfigCompatibleWithStandardLibrary
if err := json.NewDecoder(resp.Body).Decode(&keyAndOwner); err != nil {
return nil, nil, err
}
@@ -91,7 +90,7 @@ func ServCommand(ctx context.Context, keyID int64, ownerName, repoName string, m
return nil, err
}
defer resp.Body.Close()
json := jsoniter.ConfigCompatibleWithStandardLibrary
if resp.StatusCode != http.StatusOK {
var errServCommand ErrServCommand
if err := json.NewDecoder(resp.Body).Decode(&errServCommand); err != nil {

View File

@@ -7,7 +7,7 @@ package queue
import (
"reflect"
jsoniter "github.com/json-iterator/go"
"code.gitea.io/gitea/modules/json"
)
// Mappable represents an interface that can MapTo another interface
@@ -20,8 +20,6 @@ type Mappable interface {
// It will tolerate the cfg being passed as a []byte or string of a json representation of the
// exemplar or the correct type of the exemplar itself
func toConfig(exemplar, cfg interface{}) (interface{}, error) {
json := jsoniter.ConfigCompatibleWithStandardLibrary
// First of all check if we've got the same type as the exemplar - if so it's all fine.
if reflect.TypeOf(cfg).AssignableTo(reflect.TypeOf(exemplar)) {
return cfg, nil
@@ -48,7 +46,6 @@ func toConfig(exemplar, cfg interface{}) (interface{}, error) {
if !ok {
// hmm ... can we marshal it to json?
var err error
configBytes, err = json.Marshal(cfg)
ok = err == nil
}
@@ -68,7 +65,6 @@ func toConfig(exemplar, cfg interface{}) (interface{}, error) {
// unmarshalAs will attempt to unmarshal provided bytes as the provided exemplar
func unmarshalAs(bs []byte, exemplar interface{}) (data Data, err error) {
json := jsoniter.ConfigCompatibleWithStandardLibrary
if exemplar != nil {
t := reflect.TypeOf(exemplar)
n := reflect.New(t)
@@ -78,7 +74,6 @@ func unmarshalAs(bs []byte, exemplar interface{}) (data Data, err error) {
} else {
err = json.Unmarshal(bs, &data)
}
return
}

View File

@@ -12,8 +12,8 @@ import (
"sync"
"time"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
jsoniter "github.com/json-iterator/go"
)
var manager *Manager
@@ -110,7 +110,6 @@ func (m *Manager) Add(managed interface{},
configuration,
exemplar interface{}) int64 {
json := jsoniter.ConfigCompatibleWithStandardLibrary
cfg, _ := json.Marshal(configuration)
mq := &ManagedQueue{
Type: t,

View File

@@ -10,8 +10,8 @@ import (
"sync"
"time"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
jsoniter "github.com/json-iterator/go"
)
// ByteFIFOQueueConfiguration is the configuration for a ByteFIFOQueue
@@ -83,7 +83,6 @@ func (q *ByteFIFOQueue) PushFunc(data Data, fn func() error) error {
if !assignableTo(data, q.exemplar) {
return fmt.Errorf("Unable to assign data: %v to same type as exemplar: %v in %s", data, q.exemplar, q.name)
}
json := jsoniter.ConfigCompatibleWithStandardLibrary
bs, err := json.Marshal(data)
if err != nil {
return err
@@ -309,7 +308,6 @@ func (q *ByteFIFOUniqueQueue) Has(data Data) (bool, error) {
if !assignableTo(data, q.exemplar) {
return false, fmt.Errorf("Unable to assign data: %v to same type as exemplar: %v in %s", data, q.exemplar, q.name)
}
json := jsoniter.ConfigCompatibleWithStandardLibrary
bs, err := json.Marshal(data)
if err != nil {
return false, err

View File

@@ -7,7 +7,8 @@ package queue
import (
"testing"
jsoniter "github.com/json-iterator/go"
"code.gitea.io/gitea/modules/json"
"github.com/stretchr/testify/assert"
)
@@ -29,8 +30,6 @@ func TestToConfig(t *testing.T) {
assert.True(t, ok)
assert.NotEqual(t, cfg2, exemplar)
assert.Equal(t, &cfg, &cfg2)
json := jsoniter.ConfigCompatibleWithStandardLibrary
cfgString, err := json.Marshal(cfg)
assert.NoError(t, err)

View File

@@ -8,9 +8,9 @@ import (
"fmt"
"strings"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
jsoniter "github.com/json-iterator/go"
)
func validType(t string) (Type, error) {
@@ -27,8 +27,6 @@ func validType(t string) (Type, error) {
func getQueueSettings(name string) (setting.QueueSettings, []byte) {
q := setting.GetQueueSettings(name)
json := jsoniter.ConfigCompatibleWithStandardLibrary
cfg, err := json.Marshal(q)
if err != nil {
log.Error("Unable to marshall generic options: %v Error: %v", q, err)

View File

@@ -12,9 +12,9 @@ import (
"net/url"
"strings"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
jsoniter "github.com/json-iterator/go"
)
// Response is the structure of JSON returned from API
@@ -50,8 +50,8 @@ func Verify(ctx context.Context, response string) (bool, error) {
if err != nil {
return false, fmt.Errorf("Failed to read CAPTCHA response: %s", err)
}
var jsonResponse Response
json := jsoniter.ConfigCompatibleWithStandardLibrary
err = json.Unmarshal(body, &jsonResponse)
if err != nil {
return false, fmt.Errorf("Failed to parse CAPTCHA response: %s", err)

View File

@@ -8,12 +8,13 @@ import (
"fmt"
"sync"
"code.gitea.io/gitea/modules/json"
"gitea.com/go-chi/session"
couchbase "gitea.com/go-chi/session/couchbase"
memcache "gitea.com/go-chi/session/memcache"
mysql "gitea.com/go-chi/session/mysql"
postgres "gitea.com/go-chi/session/postgres"
jsoniter "github.com/json-iterator/go"
)
// VirtualSessionProvider represents a shadowed session provider implementation.
@@ -25,7 +26,6 @@ type VirtualSessionProvider struct {
// Init initializes the cookie session provider with given root path.
func (o *VirtualSessionProvider) Init(gclifetime int64, config string) error {
var opts session.Options
json := jsoniter.ConfigCompatibleWithStandardLibrary
if err := json.Unmarshal([]byte(config), &opts); err != nil {
return err
}

View File

@@ -13,14 +13,13 @@ import (
"strings"
"sync"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
jsoniter "github.com/json-iterator/go"
ini "gopkg.in/ini.v1"
)
var filenameSuffix = ""
var descriptionLock = sync.RWMutex{}
var logDescriptions = make(map[string]*LogDescription)
@@ -203,8 +202,6 @@ func generateLogConfig(sec *ini.Section, name string, defaults defaultLogOptions
}
logConfig["colorize"] = sec.Key("COLORIZE").MustBool(false)
json := jsoniter.ConfigCompatibleWithStandardLibrary
byteConfig, err := json.Marshal(logConfig)
if err != nil {
log.Error("Failed to marshal log configuration: %v %v", logConfig, err)

View File

@@ -10,8 +10,8 @@ import (
"path/filepath"
"strings"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
jsoniter "github.com/json-iterator/go"
)
var (
@@ -65,8 +65,6 @@ func newSessionService() {
default:
SessionConfig.SameSite = http.SameSiteLaxMode
}
json := jsoniter.ConfigCompatibleWithStandardLibrary
shadowConfig, err := json.Marshal(SessionConfig)
if err != nil {
log.Fatal("Can't shadow session config: %v", err)

View File

@@ -24,11 +24,11 @@ import (
"time"
"code.gitea.io/gitea/modules/generate"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/user"
"code.gitea.io/gitea/modules/util"
jsoniter "github.com/json-iterator/go"
shellquote "github.com/kballard/go-shellquote"
"github.com/unknwon/com"
gossh "golang.org/x/crypto/ssh"
@@ -1116,7 +1116,6 @@ func MakeManifestData(appName string, appURL string, absoluteAssetURL string) []
Icons []manifestIcon `json:"icons"`
}
json := jsoniter.ConfigCompatibleWithStandardLibrary
bytes, err := json.Marshal(&manifestJSON{
Name: appName,
ShortName: appName,

View File

@@ -7,7 +7,8 @@ package setting
import (
"testing"
jsoniter "github.com/json-iterator/go"
"code.gitea.io/gitea/modules/json"
"github.com/stretchr/testify/assert"
)
@@ -28,6 +29,5 @@ func TestMakeAbsoluteAssetURL(t *testing.T) {
func TestMakeManifestData(t *testing.T) {
jsonBytes := MakeManifestData(`Example App '\"`, "https://example.com", "https://example.com/foo/bar")
json := jsoniter.ConfigCompatibleWithStandardLibrary
assert.True(t, json.Valid(jsonBytes))
}

View File

@@ -7,7 +7,7 @@ package storage
import (
"reflect"
jsoniter "github.com/json-iterator/go"
"code.gitea.io/gitea/modules/json"
)
// Mappable represents an interface that can MapTo another interface
@@ -20,8 +20,6 @@ type Mappable interface {
// It will tolerate the cfg being passed as a []byte or string of a json representation of the
// exemplar or the correct type of the exemplar itself
func toConfig(exemplar, cfg interface{}) (interface{}, error) {
json := jsoniter.ConfigCompatibleWithStandardLibrary
// First of all check if we've got the same type as the exemplar - if so it's all fine.
if reflect.TypeOf(cfg).AssignableTo(reflect.TypeOf(exemplar)) {
return cfg, nil
@@ -48,7 +46,6 @@ func toConfig(exemplar, cfg interface{}) (interface{}, error) {
if !ok {
// hmm ... can we marshal it to json?
var err error
configBytes, err = json.Marshal(cfg)
ok = err == nil
}

View File

@@ -10,7 +10,7 @@ import (
"strings"
"time"
jsoniter "github.com/json-iterator/go"
"code.gitea.io/gitea/modules/json"
)
var (
@@ -132,14 +132,12 @@ type CreatePayload struct {
// JSONPayload return payload information
func (p *CreatePayload) JSONPayload() ([]byte, error) {
json := jsoniter.ConfigCompatibleWithStandardLibrary
return json.MarshalIndent(p, "", " ")
}
// ParseCreateHook parses create event hook content.
func ParseCreateHook(raw []byte) (*CreatePayload, error) {
hook := new(CreatePayload)
json := jsoniter.ConfigCompatibleWithStandardLibrary
if err := json.Unmarshal(raw, hook); err != nil {
return nil, err
}
@@ -183,7 +181,6 @@ type DeletePayload struct {
// JSONPayload implements Payload
func (p *DeletePayload) JSONPayload() ([]byte, error) {
json := jsoniter.ConfigCompatibleWithStandardLibrary
return json.MarshalIndent(p, "", " ")
}
@@ -203,7 +200,6 @@ type ForkPayload struct {
// JSONPayload implements Payload
func (p *ForkPayload) JSONPayload() ([]byte, error) {
json := jsoniter.ConfigCompatibleWithStandardLibrary
return json.MarshalIndent(p, "", " ")
}
@@ -230,7 +226,6 @@ type IssueCommentPayload struct {
// JSONPayload implements Payload
func (p *IssueCommentPayload) JSONPayload() ([]byte, error) {
json := jsoniter.ConfigCompatibleWithStandardLibrary
return json.MarshalIndent(p, "", " ")
}
@@ -261,7 +256,6 @@ type ReleasePayload struct {
// JSONPayload implements Payload
func (p *ReleasePayload) JSONPayload() ([]byte, error) {
json := jsoniter.ConfigCompatibleWithStandardLibrary
return json.MarshalIndent(p, "", " ")
}
@@ -287,14 +281,12 @@ type PushPayload struct {
// JSONPayload FIXME
func (p *PushPayload) JSONPayload() ([]byte, error) {
json := jsoniter.ConfigCompatibleWithStandardLibrary
return json.MarshalIndent(p, "", " ")
}
// ParsePushHook parses push event hook content.
func ParsePushHook(raw []byte) (*PushPayload, error) {
hook := new(PushPayload)
json := jsoniter.ConfigCompatibleWithStandardLibrary
if err := json.Unmarshal(raw, hook); err != nil {
return nil, err
}
@@ -362,7 +354,6 @@ type IssuePayload struct {
// JSONPayload encodes the IssuePayload to JSON, with an indentation of two spaces.
func (p *IssuePayload) JSONPayload() ([]byte, error) {
json := jsoniter.ConfigCompatibleWithStandardLibrary
return json.MarshalIndent(p, "", " ")
}
@@ -398,7 +389,6 @@ type PullRequestPayload struct {
// JSONPayload FIXME
func (p *PullRequestPayload) JSONPayload() ([]byte, error) {
json := jsoniter.ConfigCompatibleWithStandardLibrary
return json.MarshalIndent(p, "", " ")
}
@@ -435,6 +425,5 @@ type RepositoryPayload struct {
// JSONPayload JSON representation of the payload
func (p *RepositoryPayload) JSONPayload() ([]byte, error) {
json := jsoniter.ConfigCompatibleWithStandardLibrary
return json.MarshalIndent(p, "", " ")
}

View File

@@ -7,7 +7,7 @@ package structs
import (
"time"
jsoniter "github.com/json-iterator/go"
"code.gitea.io/gitea/modules/json"
)
// User represents a user
@@ -56,7 +56,6 @@ type User struct {
func (u User) MarshalJSON() ([]byte, error) {
// Re-declaring User to avoid recursion
type shadow User
json := jsoniter.ConfigCompatibleWithStandardLibrary
return json.Marshal(struct {
shadow
CompatUserName string `json:"username"`

View File

@@ -12,6 +12,7 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/graceful"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/migrations"
migration "code.gitea.io/gitea/modules/migrations/base"
@@ -20,7 +21,6 @@ import (
"code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
jsoniter "github.com/json-iterator/go"
)
func handleCreateError(owner *models.User, err error) error {
@@ -112,7 +112,6 @@ func runMigrateTask(t *models.Task) (err error) {
Format: format,
Args: args,
}
json := jsoniter.ConfigCompatibleWithStandardLibrary
bs, _ := json.Marshal(message)
t.Message = string(bs)
_ = t.UpdateCols("message")

View File

@@ -9,6 +9,7 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/graceful"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/migrations/base"
"code.gitea.io/gitea/modules/queue"
@@ -18,7 +19,6 @@ import (
"code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
jsoniter "github.com/json-iterator/go"
)
// taskQueue is a global queue of tasks
@@ -85,8 +85,6 @@ func CreateMigrateTask(doer, u *models.User, opts base.MigrateOptions) (*models.
return nil, err
}
opts.AuthToken = ""
json := jsoniter.ConfigCompatibleWithStandardLibrary
bs, err := json.Marshal(&opts)
if err != nil {
return nil, err

View File

@@ -8,7 +8,6 @@ package templates
import (
"bytes"
"container/list"
"encoding/json"
"errors"
"fmt"
"html"
@@ -28,6 +27,7 @@ import (
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/emoji"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/markup"
"code.gitea.io/gitea/modules/repository"
@@ -38,7 +38,6 @@ import (
"code.gitea.io/gitea/services/gitdiff"
"github.com/editorconfig/editorconfig-core-go/v2"
jsoniter "github.com/json-iterator/go"
)
// Used from static.go && dynamic.go
@@ -46,7 +45,6 @@ var mailSubjectSplit = regexp.MustCompile(`(?m)^-{3,}[\s]*$`)
// NewFuncMap returns functions for injecting to templates
func NewFuncMap() []template.FuncMap {
jsonED := jsoniter.ConfigCompatibleWithStandardLibrary
return []template.FuncMap{map[string]interface{}{
"GoVer": func() string {
return strings.Title(runtime.Version())
@@ -221,7 +219,7 @@ func NewFuncMap() []template.FuncMap {
return fmt.Sprintf("%f", float64(adds)/(float64(adds)+float64(dels))*100)
},
"Json": func(in interface{}) string {
out, err := jsonED.Marshal(in)
out, err := json.Marshal(in)
if err != nil {
return ""
}
@@ -847,7 +845,6 @@ func ActionContent2Commits(act Actioner) *repository.PushCommits {
return push
}
json := jsoniter.ConfigCompatibleWithStandardLibrary
if err := json.Unmarshal([]byte(act.GetContent()), push); err != nil {
log.Error("json.Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
}