Exemplo n.º 1
0
func initRoutes() bool {
	if inited {
		return false
	}
	inited = true

	Handle("/goroutine", "Get goroutine info",
		pprofLookupHandler("goroutine"))
	Handle("/heap", "Get heap info",
		pprofLookupHandler("heap"))
	Handle("/thread", "Get thread create info",
		pprofLookupHandler("threadcreate"))
	Handle("/block", "Get block info",
		pprofLookupHandler("block"))

	Handle("/cpu", "Get CPU info, default seconds is 30, use ?seconds= to reset",
		func(req zerver.Request, resp zerver.Response) {
			var t int
			if secs := req.Param("seconds"); secs != "" {
				var err error
				if t, err = strconv.Atoi(secs); err != nil {
					resp.ReportBadRequest()
					resp.WriteString(secs + " is not a integer number\n")
					return
				}
			}
			if t <= 0 {
				t = 30
			}
			pprof.StartCPUProfile(resp)
			time.Sleep(time.Duration(t) * time.Second)
			pprof.StopCPUProfile()
		})

	Handle("/memory", "Get memory info",
		func(req zerver.Request, resp zerver.Response) {
			runtime.GC()
			pprof.WriteHeapProfile(resp)
		})

	Handle("/routes", "Get all routes",
		func(req zerver.Request, resp zerver.Response) {
			req.Server().PrintRouteTree(resp)
		})

	Handle("/options", "Get all pprof options",
		func(req zerver.Request, resp zerver.Response) {
			if from := req.Param("from"); from != "" {
				resp.Write(unsafe2.Bytes("There is no this pprof option: " + from + "\n"))
			}
			for i := range options {
				resp.Write(unsafe2.Bytes(options[i]))
			}
		})

	return inited
}
Exemplo n.º 2
0
func base(out io.Writer, tmpl gotmpl.Tmpl, data interface{}) error {
	var err error
	_, err = out.Write(unsafe2.Bytes(``))
	if err != nil {
		return err
	}
	_, err = out.Write(unsafe2.Bytes(`

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    `))
	if err != nil {
		return err
	}
	err = tmpl.Encode(out, fmt.Sprint(data))
	if err != nil {
		return err
	}
	_, err = out.Write(unsafe2.Bytes(`
</body>
</html>

`))
	if err != nil {
		return err
	}

	err = tmpl.Encode(out, "aa")
	if err != nil {
		return err
	}
	_, err = out.Write(unsafe2.Bytes(`

`))
	if err != nil {
		return err
	}
	err = tmpl.Render(out, "tests/extend", "aa")
	if err != nil {
		return err
	}
	_, err = out.Write(unsafe2.Bytes(``))
	if err != nil {
		return err
	}

	return err
}
Exemplo n.º 3
0
// RenderTo render string to writer
func (r *Renderer) RenderTo(w io.Writer, str string) (int, error) {
	if str == "" || !r.enable {
		return w.Write(unsafe2.Bytes(str))
	}

	if err := r.Begin(w); err == nil {
		c, err := w.Write(unsafe2.Bytes(str))
		r.End(w)

		return c, err
	} else {
		return 0, err
	}
}
Exemplo n.º 4
0
func (x *Xsrf) VerifyFor(req zerver.Request) bool {
	m := req.ReqMethod()
	if !x.FilterGet && (m == zerver.METHOD_GET || m == zerver.METHOD_HEAD || m == zerver.METHOD_OPTIONS) {
		return true
	}

	token := req.GetHeader(_HEADER_XSRFTOKEN)
	if token == "" {
		token = req.GetHeader(_HEADER_CSRFTOKEN)
		if token == "" {
			token = req.Vars().QueryVar(_XSRF_PARAM_NAME)
			if token == "" {
				return false
			}
		}
	}

	data := x.verify(unsafe2.Bytes(token))
	if data != nil {
		x.Pool.Put(data)
		t, ip := x.TokenInfo.Unmarshal(data)
		return t != -1 &&
			t+x.Timeout >= time2.Now().Unix() &&
			ip == http2.IpOfAddr(req.RemoteAddr())
	}

	return false
}
Exemplo n.º 5
0
func (x *Xsrf) VerifyFor(req zerver.Request) bool {
	m := req.Method()
	if !x.FilterGet && (m == "GET" || m == "HEAD" || m == "OPTIONS") {
		return true
	}

	token := req.Header(_HEADER_XSRFTOKEN)
	if token == "" {
		token = req.Header(_HEADER_CSRFTOKEN)
		if token == "" {
			token = req.Param(_XSRF_PARAM_NAME)
			if token == "" {
				return false
			}
		}
	}

	data := x.verify(unsafe2.Bytes(token))
	if data != nil {
		x.Pool.Put(data)
		t, ip, agent := x.TokenInfo.Unmarshal(data)
		return t != -1 &&
			t+x.Timeout >= time2.Now().Unix() &&
			ip == req.RemoteIP() &&
			agent == req.UserAgent()
	}

	return false
}
Exemplo n.º 6
0
// WriteString write string to writer
func (m WriteMode) WriteString(fname, str string) (c int, err error) {
	err = file.OpenOrCreate(fname, bool(m), func(fd *os.File) error {
		c, err = fd.Write(unsafe2.Bytes(str))

		return err
	})

	return
}
Exemplo n.º 7
0
func TestCipher(t *testing.T) {
	tt := testing2.Wrap(t)
	c := NewCipher([]byte("12345"), time.Second*100, md5.New, encoding.Base64URL)

	for _, s := range []string{"a", "b", "c", "d", "e", "fdddddddddddddddddddddd"} {
		tok := c.Encode(unsafe2.Bytes(s))
		tt.Log(string(tok), len(tok))

		ds, err := c.Decode(tok)
		tt.DeepEq(unsafe2.Bytes(s), ds).Nil(err)
	}

	for _, s := range []string{"a", "b", "c", "d", ""} {
		tok := c.Encode(unsafe2.Bytes(s))
		ds, err := c.Decode(tok)
		tt.DeepEq(unsafe2.Bytes(s), ds).Nil(err)
	}
}
Exemplo n.º 8
0
// WriteL write a string list to writer, return total bytes writed
func WriteLString(w io.Writer, strs ...string) (n int, err error) {
	var c int
	for i := range strs {
		if c, err = w.Write(unsafe2.Bytes(strs[i])); err == nil {
			n += c
		} else {
			break
		}
	}

	return
}
Exemplo n.º 9
0
func (r *Renderer) RenderStringTo(w io.Writer, str ...string) (int, error) {
	err := r.Begin(w)
	var (
		n int
		c int
	)
	for i := 0; err == nil && i < len(str); i++ {
		c, err = w.Write(unsafe2.Bytes(str[i]))
		n += c
	}
	r.End(w)
	return n, err
}
Exemplo n.º 10
0
func (w Writer) Write(bs []byte) (int, error) {
	i, err := w.Writer.Write(unsafe2.Bytes(w.Prefix))
	if err != nil {
		return 0, err
	}

	n, err := w.RenderTo(w.Writer, unsafe2.String(bs))
	if err != nil {
		return 0, err
	}

	return n + i, nil
}
Exemplo n.º 11
0
func WriteIfString(w io.Writer, v interface{}) (bool, error) {
	switch s := v.(type) {
	case string:
		_, err := w.Write(unsafe2.Bytes(s))
		return true, err

	case []byte:
		_, err := w.Write(s)
		return true, err
	}

	return false, nil
}
Exemplo n.º 12
0
func WriteGZIP(w io.Writer, v interface{}) (err error) {
	gw := gzip.NewWriter(w)
	switch v := v.(type) {
	case string:
		_, err = gw.Write(unsafe2.Bytes(v))
	case []byte:
		_, err = gw.Write(v)
	default:
		err = errors.Err("Only support string and []byte")
	}
	gw.Close()

	return
}
Exemplo n.º 13
0
func BenchmarkConn(b *testing.B) {
	buf := make([]byte, 1024)
	for i := 0; i < b.N; i++ {
		fmt.Println(b.N, conn == nil)
		conn.Write(unsafe2.Bytes("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"))
		fmt.Println(b.N, conn == nil)

		n, err := conn.Read(buf)
		if err != nil {
			return
		}
		buf = buf[:n]
		buf = buf[:1024]
	}
}
Exemplo n.º 14
0
func ReadCommenttedJSON(fname, comment string, v interface{}) error {
	var trim = func(line, delim []byte) []byte {
		if len(delim) > 0 && bytes.HasPrefix(bytes.TrimSpace(line), delim) {
			return nil
		}

		return line
	}

	return file.Read(fname, func(fd *os.File) error {
		bs, err := ioutil.ReadAll(fd)
		if err != nil {
			return err
		}
		bs = bytes2.MultipleLineOperate(bs, unsafe2.Bytes(comment), trim)

		return json.Unmarshal(bs, v)
	})
}
Exemplo n.º 15
0
// printRouteTree print route tree with given parent path
func (rt *router) printRouteTree(w io.Writer, parentPath string) {
	if parentPath != "" {
		parentPath = parentPath + _PRINT_SEP
	}

	s := []byte(rt.str)
	for i := range s {
		if s[i] == _WILDCARD {
			s[i] = _MATCH_WILDCARD
		} else if s[i] == _REMAINSALL {
			s[i] = _MATCH_REMAINSALL
		}
	}

	cur := parentPath + string(s)
	if _, e := w.Write(unsafe2.Bytes(cur + "\n")); e == nil {
		rt.accessAllChilds(func(n *router) bool {
			n.printRouteTree(w, cur)
			return true
		})
	}
}
Exemplo n.º 16
0
func (c *Cipher) encrypt(now int64, str string) string {
	hash := hmac.New(c.Hash, unsafe2.Bytes(c.SecretKey))

	if now == 0 {
		now = time.Now().Add(c.TTL).UnixNano()
	}
	hash.Write(unsafe2.Bytes(str))
	hash.Write(unsafe2.Bytes(c.segSep()))
	nows := strconv.FormatInt(now, 10)
	hash.Write(unsafe2.Bytes(nows))
	hash.Write(unsafe2.Bytes(c.segSep()))
	hash.Write(unsafe2.Bytes(c.SecretKey))
	sig := hash.Sum(nil)

	sigStr := hex.EncodeToString(sig[:hash.Size()/2])
	return str + c.segSep() + nows + c.segSep() + sigStr[:len(sigStr)/2]
}
Exemplo n.º 17
0
func (r *Renderer) Fprint(w io.Writer, args ...interface{}) (int, error) {
	s := fmt.Sprint(args...)
	return r.RenderTo(w, unsafe2.Bytes(s))
}
Exemplo n.º 18
0
func WriteString(w io.Writer, s string) (int, error) {
	return w.Write(unsafe2.Bytes(s))
}
Exemplo n.º 19
0
func process(path string, wg *sync.WaitGroup) {
	sectionState := PARSE_INIT
	dataState := PARSE_INIT
	var a *API
	var sec *section
	var category string = "global"

	dataStart := 0

	err := file.Filter(path, func(linum int, line []byte) error {
		line = bytes.Replace(line, tab, tabreplace, -1)
		originLine := string(line)

		if !bytes.HasPrefix(line, unsafe2.Bytes(comment)) {
			sectionState = PARSE_INIT
			return nil
		}

		line = bytes.TrimSpace(line[len(comment):])
		line = bytes.Replace(line, []byte{'\t'}, []byte("    "), -1)
		if len(line) == 0 {
			return nil
		}

		linestr := string(line)
		switch tag := matchTag(linestr); tag {
		case TAG_CATEGORY:
			category = strings.TrimSpace(linestr[tag.Strlen():])

		case TAG_API:
			a = &API{}
			sectionState = PARSE_API
			name := strings.TrimSpace(linestr[tag.Strlen():])
			names := strings2.SplitAndTrim(name, TAG_AT_CATEGORY)
			a.name = names[0]

			if len(names) > 1 {
				as.AddAPI(names[1], a)
			} else {
				as.AddAPI(category, a)
			}
		case TAG_SUBAPI:
			a = &API{}
			sectionState = PARSE_API
			a.name = strings.TrimSpace(linestr[tag.Strlen():])

			as.AddSubAPI(a.name, a)
		case TAG_APIINCL:
			if a != nil {
				a.subapis = append(a.subapis, strings2.SplitAndTrim(linestr[tag.Strlen():], ",")...)
			}
		case TAG_ENDAPI:
			sectionState = PARSE_INIT

		case TAG_HEADER:
			sec = &section{}
			sectionState = PARSE_BODY
			dataState = PARSE_HEADER

			as.AddSubHeader(strings.TrimSpace(linestr[tag.Strlen():]), sec)
		case TAG_HEADERINCL:
			if sec != nil {
				sec.subheaders = append(sec.subheaders, strings2.SplitAndTrim(linestr[tag.Strlen():], ",")...)
			}

		case TAG_RESP:
			if sectionState != PARSE_INIT {
				sectionState = PARSE_BODY
				dataState = PARSE_STATUS
				sec = &section{}
				a.resps = append(a.resps, sec)
			}
		case TAG_SUBRESP:
			name := strings.TrimSpace(linestr[tag.Strlen():])
			sectionState = PARSE_BODY
			dataState = PARSE_STATUS
			sec = &section{}
			as.AddSubResp(name, sec)
		case TAG_RESPINCL:
			if a != nil {
				a.subresps = append(a.subresps, strings2.SplitAndTrim(linestr[tag.Strlen():], ",")...)
			}

		case TAG_REQ:
			if sectionState != PARSE_INIT {
				sectionState = PARSE_BODY
				sec = &section{}
				a.req = sec
				dataState = PARSE_STATUS
			}

		default:
			if sectionState == PARSE_INIT {
				break
			} else if sectionState == PARSE_API {
				a.desc = append(a.desc, linestr)

				break
			}

			switch dataState {
			case PARSE_STATUS:
				sec.headerLine = linestr
				dataState = PARSE_HEADER

			case PARSE_HEADER:
				if !strings.HasPrefix(linestr, TAG_DATA.String()) {
					sec.headers = append(sec.headers, linestr)

					break
				}

				dataStart = strings.Index(originLine, TAG_DATA.String()) + TAG_DATA.Strlen()
				dataState = PARSE_DATA
				fallthrough

			case PARSE_DATA:
				if len(originLine) >= dataStart {
					sec.datas = append(sec.datas, originLine[dataStart:])
				} else {
					reportErrorln("skipped data line: %s:%d:%s", path, linum, originLine)
				}
			}
		}

		return nil
	})
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
	}

	wg.Done()
}
Exemplo n.º 20
0
func (c *wsConn) WriteString(s string) (int, error) {
	return c.Write(unsafe2.Bytes(s))
}
Exemplo n.º 21
0
func (b *Buffer) WriteString(s string) (int, error) {
	return b.Write(unsafe2.Bytes(s))
}
Exemplo n.º 22
0
func (r *Renderer) End(w io.Writer) error {
	_, err := w.Write(unsafe2.Bytes(r.end))

	return err
}
Exemplo n.º 23
0
// WriteStringln write string to writer and append a newline character
func WriteStringln(w io.Writer, s string) (int, error) {
	return Writeln(w, unsafe2.Bytes(s))
}
Exemplo n.º 24
0
func (wsc *webSocketConn) WriteString(s string) (int, error) {
	return wsc.Write(unsafe2.Bytes(s))
}
Exemplo n.º 25
0
func (x *Xsrf) hash() hash.Hash {
	return hmac.New(x.HashMethod, unsafe2.Bytes(x.Secret))
}
Exemplo n.º 26
0
func (w *ErrorWriter) WriteString(s string) (int, error) {
	return w.WriteDo(unsafe2.Bytes(s), nil)
}
Exemplo n.º 27
0
func (resp *response) WriteString(s string) (int, error) {
	return resp.Write(unsafe2.Bytes(s))
}
Exemplo n.º 28
0
func (r *Router) PrintRouteTree(w io.Writer) {
	for i := range r.routers {
		w.Write(unsafe2.Bytes(r.hosts[i] + "\n"))
		r.routers[i].PrintRouteTree(w)
	}
}
Exemplo n.º 29
0
func ErrWriteString(err *error, w io.Writer, s string) {
	if *err == nil {
		_, *err = w.Write(unsafe2.Bytes(s))
	}
}
Exemplo n.º 30
0
func (r *Renderer) Begin(w io.Writer) error {
	_, err := w.Write(unsafe2.Bytes(r.settings))

	return err
}