You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
    Metadata details:
    filename: permission_handler.go
    path of file: ./repos/mayfly-go/server/pkg/req
    
    the code of the file until where you have to start completion: package req

import (
	"encoding/json"
	"fmt"
	"mayfly-go/pkg/cache"
	"mayfly-go/pkg/config"
	"mayfly-go/pkg/contextx"
	"mayfly-go/pkg/errorx"
	"mayfly-go/pkg/model"
	"mayfly-go/pkg/rediscli"
	"mayfly-go/pkg/utils/anyx"
	"strings"
	"time"
)

type Permission struct {
	NeedToken bool   // 是否需要token
	C
    
func PermissionHandler(rc *Ctx) error {
	if permissionCodeRegistry == nil {
		if rediscli.GetCli() == nil {
			permissionCodeRegistry = new(DefaultPermissionCodeRegistry)
		} else {
			permissionCodeRegistry = new(RedisPermissionCodeRegistry)
		}
	}

	var permission *Permission
	if rc.Conf != nil {
		permission = rc.Conf.requiredPermission
	}
	// 如果需要的权限信息不为空，并且不需要token，则不返回错误，继续后续逻辑
	if permission != nil && !permission.NeedToken {
		return nil
	}
	tokenStr := rc.GetHeader("Authorization")
	// 删除前缀 Bearer, 以支持 Bearer Token
	tokenStr, _ = strings.CutPrefix(tokenStr, "Bearer ")
	// header不存在则从查询参数token中获取
	if tokenStr == "" {
		tokenStr = rc.Query("token")
	}
	if tokenStr == "" {
		return errorx.PermissionErr
	}
	userId, userName, err := ParseToken(tokenStr)
	if err != nil || userId == 0 {
		return errorx.PermissionErr
	}
	// 权限不为nil，并且permission code不为空，则校验是否有权限code
	if permission != nil && permission.Code != "" {
		if !permissionCodeRegistry.HasCode(userId, permission.Code) {
			return errorx.PermissionErr
		}
	}
	rc.MetaCtx = contextx.WithLoginAccount(rc.MetaCtx, &model.LoginAccount{
		Id:       userId,
		Username: userName,
	})
	return nil
}