webserver

package
v1.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 5, 2024 License: Apache-2.0 Imports: 41 Imported by: 0

README

webserver 包的使用方法

大致流程如下,具体参考 main.go

  1. 加载配置文件,根据配置信息个性化 web server
webserver.InitWithConfigFile(path/to/configfile)
  1. 创建 app 路由
app := webserver.NewGinEngine(nil)
  1. 启动 server
webserver.Run(app)

Documentation

Index

Constants

View Source
const (
	// SaltHashids salt for hashids
	SaltHashids = "the-salt-hash-ids"
	// MinLenHashids hashid 长度
	MinLenHashids = 8
)

Variables

View Source
var (
	GettexterPoolEnglish            *sync.Pool
	GettexterPoolTraditionalChinese *sync.Pool
	GettexterPoolGerman             *sync.Pool
	GettexterPoolSpanish            *sync.Pool
	GettexterPoolFrench             *sync.Pool
	GettexterPoolItalian            *sync.Pool
	GettexterPoolJapanese           *sync.Pool
	GettexterPoolKorean             *sync.Pool
	GettexterPoolPortuguese         *sync.Pool
	GettexterPoolRussian            *sync.Pool
	GettexterPoolTurkish            *sync.Pool
	GettexterPoolVietnamese         *sync.Pool
	GettexterPoolArabic             *sync.Pool
	GettexterPoolHindi              *sync.Pool
	GettexterPoolBengali            *sync.Pool
	GettexterPoolIndonesian         *sync.Pool
	GettexterPoolThai               *sync.Pool
)

gettexter对象池

I18nLangTags i18n支持的语言列表

View Source
var TemplFuncs = map[string]interface{}{
	"_i18n": LangI18n,
	"_safe_url": func(s string) template.URL {
		return template.URL(s)
	},
	"_md2html": func(s string, ugc bool) template.HTML {
		md := goldmark.New(
			goldmark.WithParserOptions(
				parser.WithAutoHeadingID(),
			),
			goldmark.WithRendererOptions(
				html.WithHardWraps(),
				html.WithXHTML(),
			),
			goldmark.WithExtensions(
				extension.GFM,
				highlighting.NewHighlighting(
					highlighting.WithStyle("manni"),
					highlighting.WithFormatOptions(
						chromav2html.WithLineNumbers(true),
					),
				),
				&mermaid.Extender{},
				extension.Footnote,
				extension.DefinitionList,
				extension.CJK,
				extension.Typographer,
			),
		)
		if !ugc {
			md.Renderer().AddOptions(html.WithUnsafe())
		}
		buf := &bytes.Buffer{}
		if err := md.Convert([]byte(s), buf); err != nil {
			logging.Error(nil, "_md2html Convert error:"+err.Error())
			return ""
		}
		return template.HTML(buf.String())
	},
	"_url_query_escape": func(s string) string {
		return url.QueryEscape(s)
	},
	"_url_path_escape": func(s string) string {
		return url.PathEscape(s)
	},
	"_int_sum": func(ints ...int) int {
		sum := 0
		for _, i := range ints {
			sum += i
		}
		return sum
	},
	"_int_sub": func(ints ...int) int {
		if len(ints) == 0 {
			return 0
		}
		sub := ints[0]
		for _, i := range ints[1:] {
			sub -= i
		}
		return sub
	},
	"_int_mod": func(i1, i2 int) int {
		return i1 % i2
	},
	"_percent": func(i1, i2 int) int {
		if i2 == 0 {
			return 0
		}
		p := int(float64(i1) / float64(i2) * 100)
		if p == 0 {
			p = 1
		}
		return p
	},
	"_str_repeat": func(s string, count int) string {
		return strings.Repeat(s, count)
	},
	"_str_slice_join": func(s []string, sep string) string {
		return strings.Join(s, sep)
	},
	"_int_hash_encode": func(i int) string {
		return goutils.IntHashEncode(i, SaltHashids, MinLenHashids, "")
	},
	"_int32_hash_encode": func(i int32) string {
		return goutils.IntHashEncode(int(i), SaltHashids, MinLenHashids, "")
	},
	"_last_page_offset": func(total int, limit int) int {
		offset := total / limit * limit
		if offset >= total {
			offset = total - limit
		}
		return offset
	},
	"_str_cut": func(s string, cut int) string {
		r := []rune(s)
		if len(r) <= cut {
			return s
		}
		return string(r[:cut]) + "..."
	},
	"_md_clear": goutils.RemoveMarkdownTags,
	"_pbts_format": func(pbts *timestamp.Timestamp, format string) string {
		gotime, err := ptypes.Timestamp(pbts)
		if err != nil {
			logging.Error(nil, err.Error())
			return ""
		}
		loc, err := time.LoadLocation("Asia/Shanghai")
		if err != nil {
			logging.Error(nil, err.Error())
		} else {
			return gotime.In(loc).Format(format)
		}
		return gotime.Local().Format(format)
	},
	"_time_format": func(t time.Time, format string) string {
		loc, err := time.LoadLocation("Asia/Shanghai")
		if err != nil {
			logging.Error(nil, err.Error())
		} else {
			return t.In(loc).Format(format)
		}
		return t.Local().Format(format)
	},
	"_time_ago": func(ts int64, lang string) string {
		nowts := time.Now().Local().Unix()
		loc, err := time.LoadLocation("Asia/Shanghai")
		if err != nil {
			logging.Error(nil, err.Error())
		} else {
			nowts = time.Now().In(loc).Unix()
		}
		seconds := nowts - ts
		if seconds < 0 {
			seconds = 0
		}
		if seconds <= 60 {
			return fmt.Sprintf("%d%s", seconds, LangI18n(lang, "秒钟前"))
		}

		minutes := int(math.Floor(float64(seconds) / 60.0))
		if minutes <= 60 {
			return fmt.Sprintf("%d%s", minutes, LangI18n(lang, "分钟前"))
		}

		hours := int(math.Floor(float64(minutes) / 60.0))
		if hours <= 24 {
			return fmt.Sprintf("%d%s", hours, LangI18n(lang, "小时前"))
		}
		days := int(math.Floor(float64(hours) / 24.0))
		if days <= 7 {
			return fmt.Sprintf("%d%s", days, LangI18n(lang, "天前"))
		} else if days <= 31 {
			return time.Unix(ts, 0).Local().Format("01-02 15:04")
		}

		return time.Unix(ts, 0).Local().Format("2006-01-02 15:04:05")
	},
	"_gjson_get": func(js string, key string) interface{} {
		return gjson.Get(js, key).Value()
	},
	"_dict": func(values ...interface{}) (map[string]interface{}, error) {
		if len(values)%2 != 0 {
			return nil, errors.New("invalid dict call")
		}
		dict := make(map[string]interface{}, len(values)/2)
		for i := 0; i < len(values); i += 2 {
			key, ok := values[i].(string)
			if !ok {
				return nil, errors.New("dict keys must be strings")
			}
			dict[key] = values[i+1]
		}
		return dict, nil
	},
}

TemplFuncs is a template.FuncMap with functions that can be used as template actions.

Functions

func CtxI18n added in v1.5.0

func CtxI18n(c *gin.Context, msg interface{}) string

CtxI18n 从context获取多语言

func GinBasicAuth

func GinBasicAuth(args ...string) gin.HandlerFunc

GinBasicAuth gin 的基础认证中间件 加到 gin app 的路由中可以对该路由添加 basic auth 登录验证 传入 username 和 password 对可以替换默认的 username 和 password

func GinLogMiddleware

func GinLogMiddleware() gin.HandlerFunc

GinLogMiddleware 日志中间件 可根据实际需求自行修改定制

func GinRatelimitMiddleware

func GinRatelimitMiddleware() gin.HandlerFunc

GinRatelimitMiddleware 限频中间件 需先实现对应的 TODO ,可根据实际需求自行修改定制

func GinRecovery

func GinRecovery(
	recoveryHandler ...func(c *gin.Context, status int, data interface{}, err error, extraMsgs ...interface{}),
) gin.HandlerFunc

GinRecovery gin recovery 中间件 save err in context and abort with recoveryHandler

func GinSetLanguage added in v1.4.4

func GinSetLanguage(supportedLangTags ...language.Tag) gin.HandlerFunc

GinSetLanguage 设置i18n语言

func InitWithConfigFile

func InitWithConfigFile(configFile string)

InitWithConfigFile 根据 webserver 配置文件初始化 webserver

func LangI18n added in v1.5.0

func LangI18n(lang string, msg interface{}) string

LangI18n 获取多语言(模板方法使用)

func NewGinEngine

func NewGinEngine(middlewares ...gin.HandlerFunc) *gin.Engine

NewGinEngine 根据参数创建 gin 的 router engine middlewares 需要使用到的中间件列表,默认不为 engine 添加任何中间件

func PromExporterHandler

func PromExporterHandler(collectors ...prometheus.Collector) gin.HandlerFunc

PromExporterHandler return a handler as the prometheus metrics exporter

func Run

func Run(app http.Handler)

Run 以 viper 加载的 app 配置启动运行 http.Handler 的 app 注意:这里依赖 viper ,必须在外部先对 viper 配置进行加载

Types

type I18nString added in v1.5.0

type I18nString string

I18nString 需要国际化的string

func (I18nString) String added in v1.5.0

func (s I18nString) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL