️ 使用 json-iterator 替换 encoding/json 进行一些序列化/反序列化操作

This commit is contained in:
naiba 2022-03-18 23:13:22 +08:00
parent d928f65052
commit 3ca23d8d88
14 changed files with 46 additions and 37 deletions

View File

@ -4,7 +4,7 @@
<br> <br>
<small><i>LOGO designed by <a href="https://xio.ng" target="_blank">熊大</a> .</i></small> <small><i>LOGO designed by <a href="https://xio.ng" target="_blank">熊大</a> .</i></small>
<br><br> <br><br>
<img src="https://img.shields.io/github/workflow/status/naiba/nezha/Dashboard%20image?label=Dash%20v0.12.12&logo=github&style=for-the-badge">&nbsp;<img src="https://img.shields.io/github/v/release/naiba/nezha?color=brightgreen&label=Agent&style=for-the-badge&logo=github">&nbsp;<img src="https://img.shields.io/github/workflow/status/naiba/nezha/Agent%20release?label=Agent%20CI&logo=github&style=for-the-badge">&nbsp;<img src="https://img.shields.io/badge/Installer-v0.8.1-brightgreen?style=for-the-badge&logo=linux"> <img src="https://img.shields.io/github/workflow/status/naiba/nezha/Dashboard%20image?label=Dash%20v0.12.13&logo=github&style=for-the-badge">&nbsp;<img src="https://img.shields.io/github/v/release/naiba/nezha?color=brightgreen&label=Agent&style=for-the-badge&logo=github">&nbsp;<img src="https://img.shields.io/github/workflow/status/naiba/nezha/Agent%20release?label=Agent%20CI&logo=github&style=for-the-badge">&nbsp;<img src="https://img.shields.io/badge/Installer-v0.8.1-brightgreen?style=for-the-badge&logo=linux">
<br> <br>
<br> <br>
<p>:trollface: <b>哪吒监控</b> 一站式轻监控轻运维系统。支持系统状态、HTTP(SSL 证书变更、即将到期、到期)、TCP、Ping 监控报警,计划任务和在线终端。</p> <p>:trollface: <b>哪吒监控</b> 一站式轻监控轻运维系统。支持系统状态、HTTP(SSL 证书变更、即将到期、到期)、TCP、Ping 监控报警,计划任务和在线终端。</p>

View File

@ -3,7 +3,6 @@ package main
import ( import (
"context" "context"
"crypto/tls" "crypto/tls"
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"io" "io"
@ -402,7 +401,7 @@ func handleTerminalTask(task *pb.Task) {
return return
} }
var terminal model.TerminalTask var terminal model.TerminalTask
err := json.Unmarshal([]byte(task.GetData()), &terminal) err := utils.Json.Unmarshal([]byte(task.GetData()), &terminal)
if err != nil { if err != nil {
println("Terminal 任务解析错误:", err) println("Terminal 任务解析错误:", err)
return return
@ -470,7 +469,7 @@ func handleTerminalTask(task *pb.Task) {
case 0: case 0:
io.Copy(tty, reader) io.Copy(tty, reader)
case 1: case 1:
decoder := json.NewDecoder(reader) decoder := utils.Json.NewDecoder(reader)
var resizeMessage WindowSize var resizeMessage WindowSize
err := decoder.Decode(&resizeMessage) err := decoder.Decode(&resizeMessage)
if err != nil { if err != nil {

View File

@ -1,7 +1,6 @@
package monitor package monitor
import ( import (
"encoding/json"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
@ -69,7 +68,7 @@ func fetchGeoIP(servers []string, isV6 bool) geoIP {
continue continue
} }
resp.Body.Close() resp.Body.Close()
err = json.Unmarshal(body, &ip) err = utils.Json.Unmarshal(body, &ip)
if err != nil { if err != nil {
continue continue
} }

View File

@ -1,7 +1,6 @@
package controller package controller
import ( import (
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"log" "log"
@ -16,6 +15,7 @@ import (
"github.com/naiba/nezha/model" "github.com/naiba/nezha/model"
"github.com/naiba/nezha/pkg/mygin" "github.com/naiba/nezha/pkg/mygin"
"github.com/naiba/nezha/pkg/utils"
"github.com/naiba/nezha/proto" "github.com/naiba/nezha/proto"
"github.com/naiba/nezha/service/singleton" "github.com/naiba/nezha/service/singleton"
) )
@ -140,16 +140,23 @@ func (cp *commonPage) ws(c *gin.Context) {
return return
} }
defer conn.Close() defer conn.Close()
var servers []*model.Server var bytesToWrite []byte
count := 0 count := 0
for { for {
singleton.SortedServerLock.RLock() singleton.SortedServerLock.RLock()
servers = singleton.SortedServerList bytesToWrite, err = utils.Json.Marshal(Data{
singleton.SortedServerLock.RUnlock()
err = conn.WriteJSON(Data{
Now: time.Now().Unix() * 1000, Now: time.Now().Unix() * 1000,
Servers: servers, Servers: singleton.SortedServerList,
}) })
singleton.SortedServerLock.RUnlock()
if err != nil {
break
}
writer, err := conn.NextWriter(websocket.TextMessage)
if err != nil {
break
}
_, err = writer.Write(bytesToWrite)
if err != nil { if err != nil {
break break
} }
@ -241,7 +248,7 @@ func (cp *commonPage) terminal(c *gin.Context) {
return return
} }
terminalData, _ := json.Marshal(&model.TerminalTask{ terminalData, _ := utils.Json.Marshal(&model.TerminalTask{
Host: terminal.host, Host: terminal.host,
UseSSL: terminal.useSSL, UseSSL: terminal.useSSL,
Session: terminalID, Session: terminalID,

View File

@ -2,7 +2,6 @@ package controller
import ( import (
"bytes" "bytes"
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"net/http" "net/http"
@ -281,7 +280,7 @@ func (ma *memberAPI) addOrEditCron(c *gin.Context) {
cr.PushSuccessful = cf.PushSuccessful == "on" cr.PushSuccessful = cf.PushSuccessful == "on"
cr.ID = cf.ID cr.ID = cf.ID
cr.Cover = cf.Cover cr.Cover = cf.Cover
err = json.Unmarshal([]byte(cf.ServersRaw), &cr.Servers) err = utils.Json.Unmarshal([]byte(cf.ServersRaw), &cr.Servers)
} }
tx := singleton.DB.Begin() tx := singleton.DB.Begin()
if err == nil { if err == nil {
@ -433,7 +432,7 @@ func (ma *memberAPI) addOrEditAlertRule(c *gin.Context) {
var r model.AlertRule var r model.AlertRule
err := c.ShouldBindJSON(&arf) err := c.ShouldBindJSON(&arf)
if err == nil { if err == nil {
err = json.Unmarshal([]byte(arf.RulesRaw), &r.Rules) err = utils.Json.Unmarshal([]byte(arf.RulesRaw), &r.Rules)
} }
if err == nil { if err == nil {
if len(r.Rules) == 0 { if len(r.Rules) == 0 {

2
go.mod
View File

@ -16,6 +16,7 @@ require (
github.com/gorilla/websocket v1.5.0 github.com/gorilla/websocket v1.5.0
github.com/hashicorp/go-uuid v1.0.2 github.com/hashicorp/go-uuid v1.0.2
github.com/iamacarpet/go-winpty v1.0.2 github.com/iamacarpet/go-winpty v1.0.2
github.com/json-iterator/go v1.1.12
github.com/ory/graceful v0.1.2 github.com/ory/graceful v0.1.2
github.com/p14yground/go-github-selfupdate v0.0.0-20220205132106-76a6d59b925b github.com/p14yground/go-github-selfupdate v0.0.0-20220205132106-76a6d59b925b
github.com/patrickmn/go-cache v2.1.0+incompatible github.com/patrickmn/go-cache v2.1.0+incompatible
@ -47,7 +48,6 @@ require (
github.com/inconshreveable/go-update v0.0.0-20160112193335-8152e7eb6ccf // indirect github.com/inconshreveable/go-update v0.0.0-20160112193335-8152e7eb6ccf // indirect
github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.4 // indirect github.com/jinzhu/now v1.1.4 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/leodido/go-urn v1.2.1 // indirect github.com/leodido/go-urn v1.2.1 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/magiconair/properties v1.8.5 // indirect github.com/magiconair/properties v1.8.5 // indirect

View File

@ -1,9 +1,9 @@
package model package model
import ( import (
"encoding/json"
"time" "time"
"github.com/naiba/nezha/pkg/utils"
"gorm.io/gorm" "gorm.io/gorm"
) )
@ -27,7 +27,7 @@ type AlertRule struct {
} }
func (r *AlertRule) BeforeSave(tx *gorm.DB) error { func (r *AlertRule) BeforeSave(tx *gorm.DB) error {
data, err := json.Marshal(r.Rules) data, err := utils.Json.Marshal(r.Rules)
if err != nil { if err != nil {
return err return err
} }
@ -36,7 +36,7 @@ func (r *AlertRule) BeforeSave(tx *gorm.DB) error {
} }
func (r *AlertRule) AfterFind(tx *gorm.DB) error { func (r *AlertRule) AfterFind(tx *gorm.DB) error {
return json.Unmarshal([]byte(r.RulesRaw), &r.Rules) return utils.Json.Unmarshal([]byte(r.RulesRaw), &r.Rules)
} }
func (r *AlertRule) Enabled() bool { func (r *AlertRule) Enabled() bool {

View File

@ -1,9 +1,9 @@
package model package model
import ( import (
"encoding/json"
"time" "time"
"github.com/naiba/nezha/pkg/utils"
"github.com/robfig/cron/v3" "github.com/robfig/cron/v3"
"gorm.io/gorm" "gorm.io/gorm"
) )
@ -29,5 +29,5 @@ type Cron struct {
} }
func (c *Cron) AfterFind(tx *gorm.DB) error { func (c *Cron) AfterFind(tx *gorm.DB) error {
return json.Unmarshal([]byte(c.ServersRaw), &c.Servers) return utils.Json.Unmarshal([]byte(c.ServersRaw), &c.Servers)
} }

View File

@ -1,9 +1,9 @@
package model package model
import ( import (
"encoding/json"
"fmt" "fmt"
"github.com/naiba/nezha/pkg/utils"
pb "github.com/naiba/nezha/proto" pb "github.com/naiba/nezha/proto"
"github.com/robfig/cron/v3" "github.com/robfig/cron/v3"
"gorm.io/gorm" "gorm.io/gorm"
@ -66,7 +66,7 @@ func (m *Monitor) CronSpec() string {
func (m *Monitor) AfterFind(tx *gorm.DB) error { func (m *Monitor) AfterFind(tx *gorm.DB) error {
var skipServers []uint64 var skipServers []uint64
if err := json.Unmarshal([]byte(m.SkipServersRaw), &skipServers); err != nil { if err := utils.Json.Unmarshal([]byte(m.SkipServersRaw), &skipServers); err != nil {
return err return err
} }
m.SkipServers = make(map[uint64]bool) m.SkipServers = make(map[uint64]bool)
@ -82,7 +82,7 @@ func IsServiceSentinelNeeded(t uint64) bool {
func (m *Monitor) InitSkipServers() error { func (m *Monitor) InitSkipServers() error {
var skipServers []uint64 var skipServers []uint64
if err := json.Unmarshal([]byte(m.SkipServersRaw), &skipServers); err != nil { if err := utils.Json.Unmarshal([]byte(m.SkipServersRaw), &skipServers); err != nil {
return err return err
} }
m.SkipServers = make(map[uint64]bool) m.SkipServers = make(map[uint64]bool)

View File

@ -2,7 +2,6 @@ package model
import ( import (
"crypto/tls" "crypto/tls"
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
@ -10,6 +9,8 @@ import (
"net/url" "net/url"
"strings" "strings"
"time" "time"
"github.com/naiba/nezha/pkg/utils"
) )
const ( const (
@ -58,12 +59,12 @@ func (n *Notification) reqBody(message string) (string, error) {
switch n.RequestType { switch n.RequestType {
case NotificationRequestTypeJSON: case NotificationRequestTypeJSON:
return replaceParamsInString(n.RequestBody, message, func(msg string) string { return replaceParamsInString(n.RequestBody, message, func(msg string) string {
msgBytes, _ := json.Marshal(msg) msgBytes, _ := utils.Json.Marshal(msg)
return string(msgBytes)[1 : len(msgBytes)-1] return string(msgBytes)[1 : len(msgBytes)-1]
}), nil }), nil
case NotificationRequestTypeForm: case NotificationRequestTypeForm:
var data map[string]string var data map[string]string
if err := json.Unmarshal([]byte(n.RequestBody), &data); err != nil { if err := utils.Json.Unmarshal([]byte(n.RequestBody), &data); err != nil {
return "", err return "", err
} }
params := url.Values{} params := url.Values{}
@ -91,7 +92,7 @@ func (n *Notification) setRequestHeader(req *http.Request) error {
return nil return nil
} }
var m map[string]string var m map[string]string
if err := json.Unmarshal([]byte(n.RequestHeader), &m); err != nil { if err := utils.Json.Unmarshal([]byte(n.RequestHeader), &m); err != nil {
return err return err
} }
for k, v := range m { for k, v := range m {

View File

@ -1,11 +1,11 @@
package model package model
import ( import (
"encoding/json"
"fmt" "fmt"
"html/template" "html/template"
"time" "time"
"github.com/naiba/nezha/pkg/utils"
pb "github.com/naiba/nezha/proto" pb "github.com/naiba/nezha/proto"
) )
@ -39,9 +39,9 @@ func (s *Server) CopyFromRunningServer(old *Server) {
} }
func (s Server) Marshal() template.JS { func (s Server) Marshal() template.JS {
name, _ := json.Marshal(s.Name) name, _ := utils.Json.Marshal(s.Name)
tag, _ := json.Marshal(s.Tag) tag, _ := utils.Json.Marshal(s.Tag)
note, _ := json.Marshal(s.Note) note, _ := utils.Json.Marshal(s.Note)
secret, _ := json.Marshal(s.Secret) secret, _ := utils.Json.Marshal(s.Secret)
return template.JS(fmt.Sprintf(`{"ID":%d,"Name":%s,"Secret":%s,"DisplayIndex":%d,"Tag":%s,"Note":%s}`, s.ID, name, secret, s.DisplayIndex, tag, note)) // #nosec return template.JS(fmt.Sprintf(`{"ID":%d,"Name":%s,"Secret":%s,"DisplayIndex":%d,"Tag":%s,"Note":%s}`, s.ID, name, secret, s.DisplayIndex, tag, note)) // #nosec
} }

View File

@ -1,9 +1,9 @@
package model package model
import ( import (
"encoding/json"
"testing" "testing"
"github.com/naiba/nezha/pkg/utils"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -21,7 +21,7 @@ func TestServerMarshal(t *testing.T) {
} }
serverStr := string(server.Marshal()) serverStr := string(server.Marshal())
var serverRestore Server var serverRestore Server
assert.Nil(t, json.Unmarshal([]byte(serverStr), &serverRestore)) assert.Nil(t, utils.Json.Unmarshal([]byte(serverStr), &serverRestore))
assert.Equal(t, server, serverRestore) assert.Equal(t, server, serverRestore)
} }
} }

View File

@ -8,8 +8,12 @@ import (
"regexp" "regexp"
"time" "time"
"unsafe" "unsafe"
jsoniter "github.com/json-iterator/go"
) )
var Json = jsoniter.ConfigCompatibleWithStandardLibrary
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const ( const (
letterIdxBits = 6 // 6 bits to represent a letter index letterIdxBits = 6 // 6 bits to represent a letter index

View File

@ -14,7 +14,7 @@ import (
pb "github.com/naiba/nezha/proto" pb "github.com/naiba/nezha/proto"
) )
var Version = "v0.12.12" // !!记得修改 README 中的 badge 版本!! var Version = "v0.12.13" // !!记得修改 README 中的 badge 版本!!
var ( var (
Conf *model.Config Conf *model.Config