Example #1
0
// Add a frame to the database
func addFrameToDB(frame *mbus.Frame) {
	stmt, err := db.Prepare("INSERT INTO sniffedFrames (value) VALUES(?)")
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()
	stmt.Exec(frame.Value)

	// Try to update the frame in the muc table
	stmt, err = db.Prepare("UPDATE muc SET `value`=?,`timestamp`=? WHERE address=?")
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()
	stmt.Exec(frame.Value, time.Now(), frame.Identification())

	// Try to insert the frame in the muc table
	// this won't work if there is already one as the column is defined unique
	stmt, err = db.Prepare("INSERT INTO muc (`value`, `address`, `key`) VALUES(?, ?, ?)")
	if err != nil {
		log.Fatal(err)
	}
	var key string
	if frame.Address() == "440000570C37" {
		key = "CAFEBABE123456789ABCDEF0CAFEBABE"
	} else {
		key = ""
	}
	defer stmt.Close()
	stmt.Exec(frame.Value, frame.Identification(), key)
}
Example #2
0
func writeInput(conn *net.TCPConn) {
	fmt.Print("Enter username: "******"username": string(username)})
	if err != nil {
		fmt.Println("It is not property name")
		return
	}
	err = common.WriteMsg(conn, string(str))
	if err != nil {
		log.Println(err)
	}
	fmt.Println("Enter text: ")
	for {
		text, err := reader.ReadString('\n')
		if err != nil {
			log.Fatal(err)
		}
		err = common.WriteMsg(conn, username+": "+text)
		if err != nil {
			log.Println(err)
		}
	}
}
func main() {
	file, err := os.Create("samp.txt")

	if err != nil {
		log.Fatal(err)
	}
	file.WriteString("This is some random text")
	file.Close()

	stream, err := ioutil.ReadFile("samp.txt")

	if err != nil {
		log.Fatal(err)
	}

	readString := string(stream)

	fmt.Println(readString)

	randInt := 5

	// randFloat := 10.5

	randString := "100"

	// randString2 := "250.5"

	fmt.Println(float64(randInt))
	newInt, _ := strconv.ParseInt(randString, 0, 64)
	newFloat, _ := strconv.ParseFloat(randString, 64)
	fmt.Println(newInt, newFloat)
}
Example #4
0
func pullMessages(service *pubsub.Service, argv []string) {
	checkArgs(argv, 3)
	subscriptionName := fullSubscriptionName(argv[0], argv[2])
	pullRequest := &pubsub.PullRequest{
		ReturnImmediately: false,
		Subscription:      subscriptionName,
	}
	for {
		pullResponse, err := service.Subscriptions.Pull(pullRequest).Do()
		if err != nil {
			log.Fatal("Got an error while pull a message: %v", err)
		}
		if pullResponse.PubsubEvent.Message != nil {
			data, err := base64.StdEncoding.DecodeString(
				pullResponse.PubsubEvent.Message.Data)
			if err != nil {
				log.Fatal("Got an error while decoding the message: %v", err)
			}
			fmt.Printf("%s\n", data)
			ackRequest := &pubsub.AcknowledgeRequest{
				AckId:        []string{pullResponse.AckId},
				Subscription: subscriptionName,
			}
			service.Subscriptions.Acknowledge(ackRequest).Do()
		}
	}
}
Example #5
0
func main() {
	// Open device
	handle, err = pcap.OpenLive(device, snapshot_len, promiscuous, timeout)
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()

	bpfInstructions := []pcap.BPFInstruction{
		{0x20, 0, 0, 0xfffff038}, // ld rand
		{0x54, 0, 0, 0x00000004},
		{0x15, 0, 1, 0x00000004},
		{0x06, 0, 0, 0x0000ffff},
		{0x06, 0, 0, 0000000000},
	}

	err = handle.SetBPFInstructionFilter(bpfInstructions)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Capturing ~4th packet (randomly).")

	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		// Do something with a packet here.
		fmt.Println(packet)
	}

}
Example #6
0
func main() {
	if docker.SelfPath() == "/sbin/init" {
		// Running in init mode
		docker.SysInit()
		return
	}
	// FIXME: Switch d and D ? (to be more sshd like)
	flDaemon := flag.Bool("d", false, "Daemon mode")
	flDebug := flag.Bool("D", false, "Debug mode")
	flag.Parse()
	if *flDebug {
		os.Setenv("DEBUG", "1")
	}
	docker.GIT_COMMIT = GIT_COMMIT
	if *flDaemon {
		if flag.NArg() != 0 {
			flag.Usage()
			return
		}
		if err := daemon(); err != nil {
			log.Fatal(err)
		}
	} else {
		if err := runCommand(flag.Args()); err != nil {
			log.Fatal(err)
		}
	}
}
Example #7
0
func checkInput() {
	if redisPort == 0 {
		log.Fatal("Please specify the port at which the redis server is running using --port option.")
	} else if zset == "" {
		log.Fatal("Please specify the name of the ZSET to store using the --zset option.")
	}
}
Example #8
0
func (at *AuthToken) GetTokenInfo(secret string) (*TokenInfo, error) {
	/* If the token is not valid, stop now. */
	if !at.verify(secret) {
		return nil, errors.New("The token is not valid.")
	}

	/* Convert from base64. */
	jsonString, err := base64.StdEncoding.DecodeString(at.Info)
	if err != nil {
		log.Fatal("Failed to decode base64 string: ", err)
	}
	/* Unmarshal json object. */
	var ti TokenInfo
	err = json.Unmarshal(jsonString, &ti)
	if err != nil {
		log.Fatal("Failed to decode TokenInfo: ", err)
	}

	//	/* Check if the token is expired. */
	//	if time.Now().Unix() > ti.ExpirationDate.Unix() {
	//		return nil, errors.New("The token is expired.")
	//	} else {
	//		return &ti, nil
	//	}
	return &ti, nil
}
Example #9
0
func main() {
	help := fmt.Sprintf("%s link|unlink elb1 elb2 ...", os.Args[0])
	args := os.Args[1:]
	if len(args) < 2 {
		log.Fatalf("Too few arguments: %s", help)
	}
	cmd := args[0]
	elbs := args[1:]
	announcer, err := NewAnnouncer()
	if err != nil {
		log.Fatal(err)
	}
	switch cmd {
	case "link":
		err = announcer.LinkELB(elbs...)
		if err != nil {
			log.Fatal(err)
		}
	case "unlink":
		err = announcer.UnlinkELB(elbs...)
		if err != nil {
			log.Fatal(err)
		}
	default:
		log.Fatalf("Command not recognized: %s, %s", cmd, help)
	}
}
Example #10
0
func main() {
	flag.Parse()
	args := flag.Args()
	if len(args) < 2 {
		log.Fatal("too few arguments")
		return
	}
	pattern := args[0]
	filename := args[1]

	re, _ := regexp.Compile(pattern)
	file, err := os.Open(filename)
	if err != nil {
		log.Fatal(err)
		return
	}

	i := 1
	reader := bufio.NewReader(file)
	for {
		line, _, err := reader.ReadLine()
		if err == io.EOF {
			return
		}
		if re.Match(line) {
			fmt.Printf("%d: %s\n", i, string(line))
		}
		i++
	}
}
Example #11
0
func main() {
	svcConfig := &service.Config{
		Name:        "GoServiceExampleStopPause",
		DisplayName: "Go Service Example: Stop Pause",
		Description: "This is an example Go service that pauses on stop.",
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}
	if len(os.Args) > 1 {
		err = service.Control(s, os.Args[1])
		if err != nil {
			log.Fatal(err)
		}
		return
	}

	logger, err = s.Logger(nil)
	if err != nil {
		log.Fatal(err)
	}
	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
}
Example #12
0
func startMonitorFs() {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	} else {
		reloadCfg.fsWatcher = watcher
		walkFn := func(path string, info os.FileInfo, err error) error {
			if err != nil { // TODO permisstion denyed
			}
			ignore := shouldIgnore(path)
			if ignore && info.IsDir() {
				log.Println("ignore dir", path)
				return filepath.SkipDir
			}
			if info.IsDir() && !ignore {
				err = watcher.Watch(path)
				if err != nil {
					log.Fatal(err)
				} else {
					log.Println("monitoring dir", path)
				}
			}
			return nil
		}
		if err := filepath.Walk(reloadCfg.root, walkFn); err != nil {
			log.Println(err)
		}
	}
}
Example #13
0
func main() {
	flag.BoolVar(&fake, "n", false, "If true, don't actually do anything")
	flag.BoolVar(&verbose, "v", false, "Provide verbose output")
	flag.Var(&ignorePrefixes, "ignore", "Package prefix to ignore. Can be given multiple times.")
	flag.Parse()

	gopaths := filepath.SplitList(os.Getenv("GOPATH"))
	if len(gopaths) == 0 {
		log.Fatal("GOPATH must be set")
	}
	pkgName := flag.Arg(0)
	if pkgName == "" {
		log.Fatal("need a package name")
	}
	dest := flag.Arg(1)
	if dest == "" {
		log.Fatal("need a destination path")
	}

	ignorePrefixes = append(ignorePrefixes, pkgName)
	ignorePrefixes = append(ignorePrefixes, dest)
	rewrites = make(map[string]string)
	visited = make(map[string]bool)

	err := vendorize(pkgName, chooseGOPATH(gopaths, dest), dest)
	if err != nil {
		log.Fatal(err)
	}
}
Example #14
0
func setupRamDisk(path string) error {
	// err := exec.Command("umount", "-f", path).Run()
	// if err == nil {
	//   log.Printf("Unmounted ramdisk at %s - you may want to eject it!", path)
	// }

	// 1 MB
	diskPath, err := exec.Command("hdiutil", "attach", "-nomount", "ram://2048").Output()
	if err != nil {
		log.Fatal("Creating ramdisk: ", err)
	}
	diskPathStr := strings.TrimSpace(string(diskPath))
	log.Printf("Created ramdisk at %s", diskPathStr)

	err = exec.Command("newfs_hfs", diskPathStr).Run()
	if err != nil {
		log.Fatal("Formatting ramdisk: ", err)
	}
	log.Printf("Formatted ramdisk as HFS.")

	if _, err := os.Stat(path); os.IsNotExist(err) {
		err = os.Mkdir(path, 0700)
		if err != nil {
			log.Fatal("Making dir for ramdisk: ", err)
		}
	}

	err = exec.Command("mount", "-t", "hfs", diskPathStr, path).Run()
	if err != nil {
		log.Fatal("Mounting ramdisk: ", err)
	}
	log.Printf("Ramdisk mounted at %s", path)

	return nil
}
Example #15
0
func (self *app) Configure(appName string, defaultCofig interface{}) {
	self.appName = appName

	// Read config
	self.config = defaultCofig
	if err := self.parseFlags(); err != nil {
		stdlog.Fatal(err)
	}

	// Application section
	if self.appConfig != nil {
		// Set up logger
		if err := self.setupLogger(); err != nil {
			stdlog.Fatal(err)
		}

		// Set up GOMAXPROCS
		if err := self.setupGOMAXPROCS(); err != nil {
			stdlog.Fatal(err)
		}

		// Set up monitoring
		if err := self.setupMonitoring(); err != nil {
			stdlog.Fatal(err)
		}
	}

	// Common section
	// Set up metatiler
	if err := self.setupMetatiler(); err != nil {
		stdlog.Fatal(err)
	}
}
Example #16
0
func main() {
	items := []TestMessage_MsgItem{
		TestMessage_MsgItem{
			Id:        1,
			ItemName:  "aaaaa",
			ItemValue: 333,
			ItemType:  111,
		},
	}
	msg := TestMessage{
		ClientName:   "upccup",
		Description:  "test proto",
		ClientId:     1,
		Messageitems: items,
	}

	db, err := bolt.Open("bolt.db", 0644, nil)
	if err != nil {
		log.Fatal(err)
	}

	if err := PutMessages(db, &msg); err != nil {
		log.Fatal(err)
	}

	queryMsg := GetMessage(db)
	log.Printf("query msg: %+v", queryMsg)
	log.Printf("put msg: %+v", msg)
}
Example #17
0
func webSensorLocation(db data.DB, u *models.User, eventData map[string]interface{}) {
	log.Printf("%++v", eventData)
	webTag, err := tag.ForName(db, u, "WEB")
	if err != nil {
		log.Fatal(err)
	}

	lat, ok := eventData["latitude"].(float64)
	if !ok {
		return // bail
	}

	lon, ok := eventData["longitude"].(float64)
	if !ok {
		return // bail
	}

	_, _, err = event.LocationUpdate(
		db,
		u,
		0,
		lat,
		lon,
		webTag,
	)

	if err != nil {
		log.Fatal(err)
	}
}
func main() {
	zipFileName := "test.zip"

	rc, err := zip.OpenReader(zipFileName)
	if err != nil {
		log.Fatal(err)
	}

	zipFiles := rc.File
	for _, zipFile := range zipFiles {
		offset, _ := zipFile.DataOffset()
		log.Println("Compresszed:", zipFile.FileHeader.CompressedSize64, "Uncompressed:", zipFile.FileHeader.UncompressedSize64)
		log.Println(zipFile.FileHeader.Name, "\tDataOffset", offset)

		irc, err := zipFile.Open()
		if err != nil {
			log.Fatal(err)
		}

		if fileContent, err := ioutil.ReadAll(irc); err == nil {
			data := string(fileContent)
			fmt.Print(len(data), "\t", data)
		} else {
			log.Fatal(err)
		}
		irc.Close()
		fmt.Println("----------------------")
	}
}
Example #19
0
func main() {
	flag.Parse()
	b, err := parseFile(fmt.Sprintf("%s/%s.txt", *dir, *month))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Total:", b.Total)
	fmt.Println("Remaining:", b.Remaining)
	mon := *month
	year, err := strconv.Atoi(mon[0:4])
	if err != nil {
		log.Fatal(err)
	}
	m, err := strconv.Atoi(mon[4:6])
	if err != nil {
		log.Fatal(err)
	}
	rpd := b.Remaining / float64(daysIn(time.Month(m), year)-time.Now().Day())
	fmt.Printf("Remaining/day: %.2f\n", rpd)
	top := map[string]float64{}
	for _, t := range b.Transactions {
		top[t.Name] += t.Cost
	}
	fmt.Println("Top costs:")
	pl := sortMapByValue(top)
	for _, p := range pl {
		fmt.Printf("\t%s: %.2f\n", p.Key, p.Value)
	}
}
Example #20
0
func NewSenders(kind string, hosts ...string) *Senders {
	senders := &Senders{
		senders: make(map[string]Sender),
	}
	var senderClass func(backend_addr *net.UDPAddr, admin_addr *net.TCPAddr) Sender

	if kind == "udp" {
		senderClass = NewUdpSender
	} else {
		log.Fatalln("Illegal kind, should be `udp` or ...", kind)
	}

	for _, host := range hosts {
		udp_addr, err := net.ResolveUDPAddr("udp4", host)
		if err != nil {
			log.Fatal(err)
		}
		tcp_addr, err := net.ResolveTCPAddr("tcp4", host)
		if err != nil {
			log.Fatal(err)
		}
		senders.senders[host] = senderClass(udp_addr, tcp_addr)
	}
	return senders
}
Example #21
0
func main() {
	svcConfig := &service.Config{
		Name:        "ArduinoCreateBridge",
		DisplayName: "Arduino Create Bridge",
		Description: "A bridge that allows Arduino Create to operate on the boards connected to the computer",
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}
	if len(os.Args) > 1 {
		err = service.Control(s, os.Args[1])
		if err != nil {
			log.Fatal(err)
		}
		return
	}

	logger, err = s.Logger(nil)
	if err != nil {
		log.Fatal(err)
	}

	err = s.Install()
	if err != nil {
		logger.Error(err)
	}

	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
}
Example #22
0
// initRobotAccount creates a GCP robot account for this connector.
func initRobotAccount(userClient *http.Client) (string, string) {
	params := url.Values{}
	params.Set("oauth_client_id", flagToString(gcpOAuthClientIDFlag, lib.DefaultConfig.GCPOAuthClientID))

	url := fmt.Sprintf("%s%s?%s", flagToString(gcpBaseURLFlag, lib.DefaultConfig.GCPBaseURL), "createrobot", params.Encode())
	response, err := userClient.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	if response.StatusCode != 200 {
		log.Fatal("failed to initialize robot account: " + response.Status)
	}

	var robotInit struct {
		Success  bool   `json:"success"`
		Message  string `json:"message"`
		XMPPJID  string `json:"xmpp_jid"`
		AuthCode string `json:"authorization_code"`
	}

	if err = json.NewDecoder(response.Body).Decode(&robotInit); err != nil {
		log.Fatal(err)
	}
	if !robotInit.Success {
		log.Fatal("failed to initialize robot account: " + robotInit.Message)
	}

	fmt.Println("Requested OAuth credentials for robot account")

	return robotInit.XMPPJID, robotInit.AuthCode
}
Example #23
0
func GetTwitterToken(w http.ResponseWriter, r *http.Request) {
	values := r.URL.Query()
	verificationCode := values.Get("oauth_verifier")
	tokenKey := values.Get("oauth_token")

	accessToken, err := c.AuthorizeToken(tokens[tokenKey], verificationCode)
	if err != nil {
		log.Fatal(err)
	}

	client, err := c.MakeHttpClient(accessToken)
	if err != nil {
		log.Fatal(err)
	}

	response, err := client.Get(
		"https://api.twitter.com/1.1/statuses/home_timeline.json?count=1")
	if err != nil {
		log.Fatal(err)
	}
	defer response.Body.Close()

	bits, err := ioutil.ReadAll(response.Body)
	fmt.Fprintf(w, "The newest item in your home timeline is: "+string(bits))
}
Example #24
0
func ExampleThrottler() {
	ln, err := net.Listen("tcp", ":6789")
	if err != nil {
		log.Fatal(err)
	}
	th := NewThrottler(100 * time.Millisecond)
	defer th.Close()

	echo := func(conn net.Conn) {
		defer conn.Close()

		host, port, err := net.SplitHostPort(conn.RemoteAddr().String())
		if err != nil {
			panic(err)
		}
		// Throttle to 10 connection per second from the same host
		// Handle non-conformity by dropping the connection
		if th.Halt(host, 1, 10) {
			log.Printf("Throttled %s", host)
			return
		}
		log.Printf("Echoing payload from %s:%s", host, port)
		io.Copy(conn, conn)
	}

	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Fatal(err)
		}
		go echo(conn)
	}
}
Example #25
0
func main() {
	flag.Usage = usage
	flag.Parse()

	if flag.NArg() == 0 {
		// Read from stdin
		if err := display(os.Stdin); err != nil {
			log.Fatal(err)
		}
	} else {
		for _, filename := range flag.Args() {
			// Skip errors and directories
			if fi, err := os.Stat(filename); err != nil || fi.IsDir() {
				continue
			}

			f, err := os.Open(filename)
			if err != nil {
				log.Fatal(err)
			}
			defer f.Close()

			if err := display(f); err != nil {
				log.Fatal(err)
			}
		}
	}
}
Example #26
0
func runDevelopmentServer(path string) {
	if len(path) < 1 {
		printHelpCommand("A GAEA project directory must be specified:")
		return
	}

	verified := verifyAppServerExists()
	if !verified {
		return
	}
	fmt.Fprintln(os.Stdout, "Running Dev App Server through GAEA...")
	cmd := exec.Command("dev_appserver.py", path)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		log.Fatal(err)
	}
	stderr, err := cmd.StderrPipe()
	if err != nil {
		log.Fatal(err)
	}
	if err := cmd.Start(); err != nil {
		log.Fatal(err)
	}
	go io.Copy(os.Stdout, stdout)
	go io.Copy(os.Stderr, stderr)
	if err := cmd.Wait(); err != nil {
		log.Fatal(err)
	}
}
Example #27
0
File: watch.go Project: zmdroid/bee
func NewWatcher(paths []string) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		for {
			select {
			case e := <-watcher.Event:
				fmt.Println(e)
				go Autobuild()
			case err := <-watcher.Error:
				log.Fatal("error:", err)
			}
		}
	}()
	for _, path := range paths {
		fmt.Println(path)
		err = watcher.Watch(path)
		if err != nil {
			log.Fatal(err)
		}
	}

}
Example #28
0
func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage: ", os.Args[0], "server")
		os.Exit(1)
	}
	serverAddress := os.Args[1]

	client, err := rpc.DialHTTP("tcp", serverAddress+":1234")
	if err != nil {
		log.Fatal("dialing", err)
	}

	// Synchronous call
	args := rpc_common.Args{17, 8}
	var reply int
	err = client.Call("Arith.Multiply", args, &reply)
	if err != nil {
		log.Fatal("arith error:", err)
	}
	fmt.Printf("Arith: %d*%d=%d\n", args.A, args.B, reply)

	var quot rpc_common.Quotient
	err = client.Call("Arith.Divide", args, &quot)
	if err != nil {
		log.Fatal("arith error:", err)
	}
	fmt.Printf("Arith: %d/%d=%d reminder %d\n",
		args.A, args.B, quot.Quo, quot.Rem)
}
Example #29
0
func main() {
	var longUrl string
	longUrl = os.Args[len(os.Args)-1]

	body := bytes.NewBufferString(fmt.Sprintf(`{"longUrl":"%s"}`, longUrl))
	request, err := http.NewRequest("POST",
		"https://www.googleapis.com/urlshortener/v1/url",
		body)

	request.Header.Add("Content-Type", "application/json")

	client := http.Client{}
	response, err := client.Do(request)

	if err != nil {
		log.Fatal(err)
	}

	outputAsBytes, err := ioutil.ReadAll(response.Body)
	response.Body.Close()

	var output apiResponse
	err = json.Unmarshal(outputAsBytes, &output)

	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s\n", output.Id)
}
Example #30
0
func ExampleReader() {
	// Open a zip archive for reading.
	r, err := zip.OpenReader("testdata/readme.zip")
	if err != nil {
		log.Fatal(err)
	}
	defer r.Close()

	// Iterate through the files in the archive,
	// printing some of their contents.
	for _, f := range r.File {
		fmt.Printf("Contents of %s:\n", f.Name)
		rc, err := f.Open()
		if err != nil {
			log.Fatal(err)
		}
		_, err = io.CopyN(os.Stdout, rc, 68)
		if err != nil {
			log.Fatal(err)
		}
		rc.Close()
		fmt.Println()
	}
	// Output:
	// Contents of README:
	// This is the source code repository for the Go programming language.
}