Skip to content
Myr

utils.go

This file

Path

utils.go

189 lines · 4.2 KiB · Go

Last changed by

docs: align function comments with names (#4814)daixiheguubefore adoptione318c6a

History of this file

Take it

1// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package gin67import (8	"encoding/xml"9	"math"10	"net/http"11	"os"12	"path"13	"reflect"14	"runtime"15	"strings"16	"unicode"17)1819// BindKey indicates a default bind key.20const BindKey = "_gin-gonic/gin/bindkey"2122// localhostIP indicates the default localhost IP address.23const localhostIP = "127.0.0.1"2425// localhostIPv6 indicates the default localhost IPv6 address.26const localhostIPv6 = "::1"2728// Bind is a helper function for given interface object and returns a Gin middleware.29// It panics if val is a pointer; pass the struct value directly (e.g., gin.Bind(Struct{}) not gin.Bind(&Struct{})).30func Bind(val any) HandlerFunc {31	value := reflect.ValueOf(val)32	if value.Kind() == reflect.Ptr {33		panic(`Bind struct can not be a pointer. Example:34	Use: gin.Bind(Struct{}) instead of gin.Bind(&Struct{})35`)36	}37	typ := value.Type()3839	return func(c *Context) {40		obj := reflect.New(typ).Interface()41		if c.Bind(obj) == nil {42			c.Set(BindKey, obj)43		}44	}45}4647// WrapF is a helper function for wrapping http.HandlerFunc and returns a Gin middleware.48func WrapF(f http.HandlerFunc) HandlerFunc {49	return func(c *Context) {50		f(c.Writer, c.Request)51	}52}5354// WrapH is a helper function for wrapping http.Handler and returns a Gin middleware.55func WrapH(h http.Handler) HandlerFunc {56	return func(c *Context) {57		h.ServeHTTP(c.Writer, c.Request)58	}59}6061// H is a shortcut for map[string]any62type H map[string]any6364// MarshalXML allows type H to be used with xml.Marshal.65func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error {66	start.Name = xml.Name{67		Space: "",68		Local: "map",69	}70	if err := e.EncodeToken(start); err != nil {71		return err72	}73	for key, value := range h {74		elem := xml.StartElement{75			Name: xml.Name{Space: "", Local: key},76			Attr: []xml.Attr{},77		}78		if err := e.EncodeElement(value, elem); err != nil {79			return err80		}81	}8283	return e.EncodeToken(xml.EndElement{Name: start.Name})84}8586func assert1(guard bool, text string) {87	if !guard {88		panic(text)89	}90}9192func filterFlags(content string) string {93	for i, char := range content {94		if char == ' ' || char == ';' {95			return content[:i]96		}97	}98	return content99}100101func chooseData(custom, wildcard any) any {102	if custom != nil {103		return custom104	}105	if wildcard != nil {106		return wildcard107	}108	panic("negotiation config is invalid")109}110111func parseAccept(acceptHeader string) []string {112	parts := strings.Split(acceptHeader, ",")113	out := make([]string, 0, len(parts))114	for _, part := range parts {115		if i := strings.IndexByte(part, ';'); i > 0 {116			part = part[:i]117		}118		if part = strings.TrimSpace(part); part != "" {119			out = append(out, part)120		}121	}122	return out123}124125func lastChar(str string) uint8 {126	if str == "" {127		panic("The length of the string can't be 0")128	}129	return str[len(str)-1]130}131132func nameOfFunction(f any) string {133	return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()134}135136func joinPaths(absolutePath, relativePath string) string {137	if relativePath == "" {138		return absolutePath139	}140141	finalPath := path.Join(absolutePath, relativePath)142	if lastChar(relativePath) == '/' && lastChar(finalPath) != '/' {143		return finalPath + "/"144	}145	return finalPath146}147148func resolveAddress(addr []string) string {149	switch len(addr) {150	case 0:151		if port := os.Getenv("PORT"); port != "" {152			debugPrint("Environment variable PORT=\"%s\"", port)153			return ":" + port154		}155		debugPrint("Environment variable PORT is undefined. Using port :8080 by default")156		return ":8080"157	case 1:158		return addr[0]159	default:160		panic("too many parameters")161	}162}163164// isASCII reports whether s contains only ASCII characters.165// See https://stackoverflow.com/questions/53069040/checking-a-string-contains-only-ascii-characters.166func isASCII(s string) bool {167	for i := range len(s) {168		if s[i] > unicode.MaxASCII {169			return false170		}171	}172	return true173}174175// safeInt8 converts int to int8 safely, capping at math.MaxInt8176func safeInt8(n int) int8 {177	if n > math.MaxInt8 {178		return math.MaxInt8179	}180	return int8(n)181}182183// safeUint16 converts int to uint16 safely, capping at math.MaxUint16184func safeUint16(n int) uint16 {185	if n > math.MaxUint16 {186		return math.MaxUint16187	}188	return uint16(n)189}