handlers.go 1.6 KB
package tool

import (
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"path/filepath"
	"strings"
)

func LogHandler(conf logx.LogConf) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req struct {
			Module string `path:"module"`
		}
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		path := conf.Path
		if conf.Mode != "file" {
			return
		}
		if path == "" {
			path = "logs"
		}
		if !strings.HasSuffix(req.Module, ".log") {
			req.Module += ".log"
		}
		handler := http.FileServer(http.Dir(path))
		r.URL.Path = filepath.Join(req.Module)
		handler.ServeHTTP(w, r)
	}
}

func ClearCacheHandler(redis *redis.Redis) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var (
			success int
			appName string
		)
		var req struct {
			App string `path:"app"`
		}
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		appName = req.App
		if strings.TrimSpace(appName) == "" {
			httpx.Ok(w)
			return
		}
		keyPattern := fmt.Sprintf("%s*", appName)
		list, err := redis.Keys(keyPattern)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		}
		for _, key := range list {
			if _, err = redis.Del(key); err == nil {
				success++
			}
		}
		logx.Infof("清理缓存:%d/%d", success, len(list))

		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJson(w, fmt.Sprintf("应用:%v 清理缓存:%d/%d", appName, success, len(list)))
		}
	}
}