欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

Golang写了一个帮助调试的代理程序,PHP实现了一个类用于输出调

程序员文章站 2022-05-15 12:01:13
...

1.有时,我们想看到对于同一个URL请求多次,输出的调试信息的变化。 2.或者当你调试的脚本需要重定向到其他脚本,然后又重定向回来,你希望能看到这些脚本的调试输出信息。 3.当你的脚本通过CURL请求一个自己设计的API时,你想输出这个API的一些调试信息。 那

1.有时,我们想看到对于同一个URL请求多次,输出的调试信息的变化。
2.或者当你调试的脚本需要重定向到其他脚本,然后又重定向回来,你希望能看到这些脚本的调试输出信息。
3.当你的脚本通过CURL请求一个自己设计的API时,你想输出这个API的一些调试信息。

那么这个代理程序将能够帮到你,但它现在只能简单的输出一些调试信息,它仍需要完善。
详细介绍:https://github.com/yangxikun/proxy-debug/blob/master/README_zh-CN.md
目前仅支持linux,因为使用到了shell的字符颜色功能

源码与演示:源码出处


 * @copyright 2014 kun
 * @license   http://www.php.net/license/3_01.txt  PHP License 3.01
 * @version   1.0
 * @link      https://github.com/yangxikun/tag-parse
 * @since     1.0
 */
/**
* PD
*
* @author    rokety 
* @license   http://www.php.net/license/3_01.txt  PHP License 3.01
* @version   1.0
* @link
* @since     1.0
*/
class PD
{
    protected static $debugItemCount = 0;
    protected static $debugGroupCount = 0;
    protected static $group = array();
    protected static $start;
    protected static $offset = 0;
    protected static $varNameString = null;

    /**
     * getVarName
     * get the variable name
     *
     * @access protected
     * @static
     *
     * @return string
     */
    protected static function getVarName()
    {
        if (self::$varNameString === null) {
            $trace = debug_backtrace();
            $line = file($trace[3]['file']);
            self::$varNameString = $line[$trace[3]['line']-1];
        }

        preg_match(
            '~\$([\w\d_]+)~',
            self::$varNameString,
            $matches,
            PREG_OFFSET_CAPTURE,
            self::$offset
        );

        if (!isset($matches[1])) {
            throw new Exception('Error Params, should use $variable as params', 1);
        }
        self::$offset = $matches[1][1];

        return $matches[1][0];
    }

    /**
     * func
     *
     * @param string $type debug type(info, warn, error)
     * @param mixed  $arg  debug variable
     *
     * @access protected
     * @static
     *
     * @return null
     */
    protected static function func($type, $arg)
    {
        if (self::$start) {
            self::$group[] = array(
                "category"=>$type,
                "type"=>gettype($arg),
                "name"=>self::getVarName(),
                "value"=>$arg
            );
        } else {
            self::$debugItemCount++;
            header(
                'Proxy_debug_item_'.self::$debugItemCount.': '
                .json_encode(
                    ["category"=>$type,
                    "type"=>gettype($arg),
                    "name"=>self::getVarName(),
                    "value"=>$arg]
                )
            );
            header('Proxy_debug_item_count: '.self::$debugItemCount);
        }
    }

    public static function __callStatic($name, $args)
    {
        $func = ['info'=>'I', 'warn'=>'W', 'error'=>'E'];
        if (isset($func[$name])) {
            self::$offset = 0;
            self::$varNameString = null;
            foreach ($args as $key => $arg) {
                self::func($func[$name], $arg);
            }
        } else {
            throw new Exception('Call to undefined method!', 1);
        }
    }

    /**
     * groupStart
     * start record a group
     *
     * @access public
     * @static
     *
     * @return null
     */
    public static function groupStart()
    {
        self::$start = true;
        self::$debugGroupCount++;
    }

    /**
     * groupEnd
     * stop record a group
     *
     * @access public
     * @static
     *
     * @return null
     */
    public static function groupEnd()
    {
        self::$start = false;
        header(
            'Proxy_debug_group_'
            .self::$debugGroupCount
            .': '.json_encode(self::$group)
        );
        header('Proxy_debug_group_count: '.self::$debugGroupCount);
        self::$group = array();
    }
}
//Proxy Debug
//This simple program is for helping developers debug through http header.
//For more detail, see README.md

package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
)

//color config
var color map[string]interface{}

//Parse config file
func readConfig() {
	config, err := os.Open("config.ini")
	if err != nil {
		log.Fatalln(err)
	}

	buf := bufio.NewReader(config)
	line, _ := buf.ReadString('\n')

	var jsonData interface{}
	err = json.Unmarshal([]byte(line), &jsonData)
	if err != nil {
		log.Fatalln(err)
	}
	var ok bool
	color, ok = jsonData.(map[string]interface{})
	if ok == false {
		log.Fatalln("Parse config file error, it must be a json string!")
	}
	for _, c := range color {
		if c.(float64) > 37 || c.(float64)  65535 || port  maxLenName {
					maxLenName = len(v)
				}
				v = vm["type"].(string)
				if len(v) > maxLenType {
					maxLenType = len(v)
				}
			}

			for _, i := range debugItemIndex {
				n := debugItem[i]["name"].(string)
				t := debugItem[i]["type"].(string)
				c := debugItem[i]["category"].(string)
				fmt.Printf(
					format,
					caterory[c],
					c,
					color["varName"],
					n+strings.Repeat(" ", maxLenName-len(n)+1),
					color["varType"],
					t+strings.Repeat(" ", maxLenType-len(t)+1),
					color["varValue"],
					strings.Replace(fmt.Sprint(debugItem[i]["value"]), "map", "", 1))
			}
		}

		if okDebugGroup {
			if okDebugItem == false {
				fmt.Printf("\033[%vm%v\n", color["url"], r.URL)
			}
			maxLenName := make([]int, len(debugGroupIndex))
			maxLenType := make([]int, len(debugGroupIndex))
			k := 0
			for _, vm := range debugGroup {
				for _, vv := range vm.([]interface{}) {
					vk, ok := vv.(map[string]interface{})
					if ok == false {
						continue
					}
					v := vk["name"].(string)
					if len(v) > maxLenName[k] {
						maxLenName[k] = len(v)
					}
					v = vk["type"].(string)
					if len(v) > maxLenType[k] {
						maxLenType[k] = len(v)
					}
				}
				k++
			}

			k = 0
			for _, i := range debugGroupIndex {
				fmt.Printf("\t\033[%vm=Group %v=\n", color["group"], k+1)
				for _, v := range debugGroup[i].([]interface{}) {
					vk, ok := v.(map[string]interface{})
					if ok == false {
						continue
					}
					n := vk["name"].(string)
					t := vk["type"].(string)
					c := vk["category"].(string)
					fmt.Printf(
						format,
						caterory[c],
						c,
						color["varName"],
						n+strings.Repeat(" ", maxLenName[k]-len(n)+1),
						color["varType"],
						t+strings.Repeat(" ", maxLenType[k]-len(t)+1),
						color["varValue"],
						strings.Replace(fmt.Sprint(vk["value"]), "map", "", 1))
				}
				k++
				fmt.Printf("\t\033[%vm=GROUP=\n", color["group"])
			}
		}
	})
	http.ListenAndServe(":"+strconv.Itoa(port), nil)
}
Golang写了一个帮助调试的代理程序,PHP实现了一个类用于输出调