Table of Contents
" >2. [文件] main.go ~ 6KB      
Home php教程 PHP源码 Golang写了一个帮助调试的代理程序,PHP实现了一个类用于输出调试信息

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

May 25, 2016 pm 04:59 PM

        跳至          

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

<?php

/**

 * PD

 * ProxyDebug

 *

 * @author    kun* @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][&#39;file&#39;]);

            self::$varNameString = $line[$trace[3][&#39;line&#39;]-1];

        }

 

        preg_match(

            &#39;~\$([\w\d_]+)~&#39;,

            self::$varNameString,

            $matches,

            PREG_OFFSET_CAPTURE,

            self::$offset

        );

 

        if (!isset($matches[1])) {

            throw new Exception(&#39;Error Params, should use $variable as params&#39;, 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(

                &#39;Proxy_debug_item_&#39;.self::$debugItemCount.&#39;: &#39;

                .json_encode(

                    ["category"=>$type,

                    "type"=>gettype($arg),

                    "name"=>self::getVarName(),

                    "value"=>$arg]

                )

            );

            header(&#39;Proxy_debug_item_count: &#39;.self::$debugItemCount);

        }

    }

 

    public static function __callStatic($name, $args)

    {

        $func = [&#39;info&#39;=>&#39;I&#39;, &#39;warn&#39;=>&#39;W&#39;, &#39;error&#39;=>&#39;E&#39;];

        if (isset($func[$name])) {

            self::$offset = 0;

            self::$varNameString = null;

            foreach ($args as $key => $arg) {

                self::func($func[$name], $arg);

            }

        } else {

            throw new Exception(&#39;Call to undefined method!&#39;, 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(

            &#39;Proxy_debug_group_&#39;

            .self::$debugGroupCount

            .&#39;: &#39;.json_encode(self::$group)

        );

        header(&#39;Proxy_debug_group_count: &#39;.self::$debugGroupCount);

        self::$group = array();

    }

}

Copy after login

2. [文件] main.go ~ 6KB

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

//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(&#39;\n&#39;)

 

    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) < 30 {

            log.Fatalln("Config error!The valid value is 30-37.")

        }

    }

    item := [5]string{"url", "varName", "varType", "varValue", "group"}

    for _, i := range item {

        _, has := color[i]

        if has == false {

            log.Fatalln("Losing configuration:", i)

        }

    }

}

 

func main() {

    var port int = 8888

 

    if len(os.Args) == 1 {

        fmt.Println("Listening in default port:8888")

    } else if os.Args[1] == "--help" {

        fmt.Println("usage: proxy [-p port]")

        return

    } else if len(os.Args) != 3 || os.Args[1] != "-p" {

        log.Fatalln("Error arguments!Just support &#39;-p port&#39;.")

    } else {

        port, err := strconv.Atoi(os.Args[2])

        if err != nil && port > 65535 || port < 1024 {

            log.Fatalln("Error port, it should be 1024-65535, default is 8888.")

        }

    }

 

    readConfig()

 

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

        r.RequestURI = ""

        resp, err := http.DefaultClient.Do(r)

        if err != nil {

            http.NotFound(w, r)

            return

        }

        defer resp.Body.Close()

 

        //Get the debugging information form http header

        caterory := map[string]int{"I": 34, "W": 33, "E": 31}

        format := "\t \033[%dm-%s\033[%vm %s\033[%vm%s\033[%vm%s\n"

        debugItem := make(map[string]map[string]interface{})

        debugItemIndex := make([]string, 0, 5)

        var jsonData interface{}

 

        v, okDebugItem := resp.Header["Proxy_debug_item_count"]

        if okDebugItem {

            count, _ := strconv.Atoi(v[0])

            for i := 1; i <= count; i++ {

                index := "Proxy_debug_item_" + strconv.Itoa(i)

                vv, ok := resp.Header[index]

                if ok {

                    err = json.Unmarshal([]byte(vv[0]), &jsonData)

                    if err != nil {

                        continue

                    }

                    data, ok := jsonData.(map[string]interface{})

                    if ok == false {

                        continue

                    }

                    debugItemIndex = append(debugItemIndex, index)

                    debugItem[index] = data

                }

            }

        }

 

        debugGroup := make(map[string]interface{})

        debugGroupIndex := make([]string, 0, 5)

 

        v, okDebugGroup := resp.Header["Proxy_debug_group_count"]

        if okDebugGroup {

            count, _ := strconv.Atoi(v[0])

            for i := 1; i  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)

}

Copy after login

                           

           

           

3. [图片] screenshot.pngGolang写了一个帮助调试的代理程序,PHP实现了一个类用于输出调试信息    

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

                   

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)