refactor(utils): move util functions to utils.go

This commit is contained in:
OHZEKI Naoki 2025-12-11 00:20:14 +09:00
parent 19b877fa50
commit ab7e69e374
4 changed files with 28 additions and 17 deletions

View File

@ -55,14 +55,6 @@ const ContextRequestKey ContextKeyType = 0
// abortIndex represents a typical value used in abort functions. // abortIndex represents a typical value used in abort functions.
const abortIndex int8 = math.MaxInt8 >> 1 const abortIndex int8 = math.MaxInt8 >> 1
// safeInt8 converts int to int8 safely, capping at math.MaxInt8
func safeInt8(n int) int8 {
if n > math.MaxInt8 {
return math.MaxInt8
}
return int8(n)
}
// Context is the most important part of gin. It allows us to pass variables between middleware, // Context is the most important part of gin. It allows us to pass variables between middleware,
// manage the flow, validate the JSON of a request and render a JSON response for example. // manage the flow, validate the JSON of a request and render a JSON response for example.
type Context struct { type Context struct {

View File

@ -5,7 +5,6 @@
package gin package gin
import ( import (
"math"
"net/url" "net/url"
"strings" "strings"
"unicode" "unicode"
@ -78,14 +77,6 @@ func (n *node) addChild(child *node) {
} }
} }
// safeUint16 converts int to uint16 safely, capping at math.MaxUint16
func safeUint16(n int) uint16 {
if n > math.MaxUint16 {
return math.MaxUint16
}
return uint16(n)
}
func countParams(path string) uint16 { func countParams(path string) uint16 {
colons := strings.Count(path, ":") colons := strings.Count(path, ":")
stars := strings.Count(path, "*") stars := strings.Count(path, "*")

View File

@ -6,6 +6,7 @@ package gin
import ( import (
"encoding/xml" "encoding/xml"
"math"
"net/http" "net/http"
"os" "os"
"path" "path"
@ -162,3 +163,19 @@ func isASCII(s string) bool {
} }
return true return true
} }
// safeInt8 converts int to int8 safely, capping at math.MaxInt8
func safeInt8(n int) int8 {
if n > math.MaxInt8 {
return math.MaxInt8
}
return int8(n)
}
// safeUint16 converts int to uint16 safely, capping at math.MaxUint16
func safeUint16(n int) uint16 {
if n > math.MaxUint16 {
return math.MaxUint16
}
return uint16(n)
}

View File

@ -8,6 +8,7 @@ import (
"bytes" "bytes"
"encoding/xml" "encoding/xml"
"fmt" "fmt"
"math"
"net/http" "net/http"
"testing" "testing"
@ -148,3 +149,13 @@ func TestIsASCII(t *testing.T) {
assert.True(t, isASCII("test")) assert.True(t, isASCII("test"))
assert.False(t, isASCII("🧡💛💚💙💜")) assert.False(t, isASCII("🧡💛💚💙💜"))
} }
func TestSafeInt8(t *testing.T) {
assert.Equal(t, int8(100), safeInt8(100))
assert.Equal(t, int8(math.MaxInt8), safeInt8(int(math.MaxInt8)+123))
}
func TestSafeUint16(t *testing.T) {
assert.Equal(t, uint16(100), safeUint16(100))
assert.Equal(t, uint16(math.MaxUint16), safeUint16(int(math.MaxUint16)+123))
}