コード例 #1
0
ファイル: main.go プロジェクト: EricBurnett/WebCmd
func main() {
	flag.Parse()

	// Redirect log output to file.
	_, prog := filepath.Split(os.Args[0])
	log_path := filepath.Join(os.TempDir(), prog+".INFO")
	w, err := os.OpenFile(log_path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
	if err == nil {
		log.Print("Setting log output to ", log_path)
		log.SetOutput(w)
		log.Print("Logfile created")
	} else {
		log.Print("Failed to redirect output: ", err)
	}

	serverURL := ServeAsync()

	block := !*window
	if *window {
		if err := platform.WebviewWindow(serverURL); err != nil {
			log.Print(err)
			block = true
		}
	}
	// If we're not starting a window (or it failed), block forever instead.
	if block {
		select {}
	}
	log.Println("Main done, terminating.")
}
コード例 #2
0
ファイル: app.go プロジェクト: kryptBlue/gotty
func (app *App) handleWS(w http.ResponseWriter, r *http.Request) {
	log.Printf("New client connected: %s", r.RemoteAddr)

	if r.Method != "GET" {
		http.Error(w, "Method not allowed", 405)
		return
	}

	conn, err := app.upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Print("Failed to upgrade connection")
		return
	}

	cmd := exec.Command(app.options.Command[0], app.options.Command[1:]...)
	ptyIo, err := pty.Start(cmd)
	if err != nil {
		log.Print("Failed to execute command")
		return
	}
	log.Printf("Command is running for client %s with PID %d", r.RemoteAddr, cmd.Process.Pid)

	context := &clientContext{
		app:        app,
		request:    r,
		connection: conn,
		command:    cmd,
		pty:        ptyIo,
	}

	context.goHandleClient()
}
コード例 #3
0
ファイル: clipboard.go プロジェクト: joy999/walk
func main() {
	var te *walk.TextEdit

	if _, err := (MainWindow{
		Title:   "Walk Clipboard Example",
		MinSize: Size{300, 200},
		Layout:  VBox{},
		Children: []Widget{
			PushButton{
				Text: "Copy",
				OnClicked: func() {
					if err := walk.Clipboard().SetText(te.Text()); err != nil {
						log.Print("Copy: ", err)
					}
				},
			},
			PushButton{
				Text: "Paste",
				OnClicked: func() {
					if text, err := walk.Clipboard().Text(); err != nil {
						log.Print("Paste: ", err)
					} else {
						te.SetText(text)
					}
				},
			},
			TextEdit{
				AssignTo: &te,
			},
		},
	}).Run(); err != nil {
		log.Fatal(err)
	}
}
コード例 #4
0
ファイル: storage_csv.go プロジェクト: nikbyte/cgrates
func (csvs *CSVStorage) GetTpCdrStats(tpid, tag string) ([]TpCdrstat, error) {
	csvReader, fp, err := csvs.readerFunc(csvs.cdrStatsFn, csvs.sep, getColumnCount(TpCdrstat{}))
	if err != nil {
		log.Print("Could not load cdr stats file: ", err)
		// allow writing of the other values
		return nil, nil
	}
	if fp != nil {
		defer fp.Close()
	}
	var tpCdrStats []TpCdrstat
	for record, err := csvReader.Read(); err != io.EOF; record, err = csvReader.Read() {
		if err != nil {
			log.Print("bad line in cdr stats csv: ", err)
			return nil, err
		}
		if tpCdrStat, err := csvLoad(TpCdrstat{}, record); err != nil {
			log.Print("error loading cdr stat: ", err)
			return nil, err
		} else {
			cs := tpCdrStat.(TpCdrstat)
			cs.Tpid = tpid
			tpCdrStats = append(tpCdrStats, cs)
		}
	}
	return tpCdrStats, nil
}
コード例 #5
0
ファイル: storage_csv.go プロジェクト: nikbyte/cgrates
func (csvs *CSVStorage) GetTpTimings(tpid, tag string) ([]TpTiming, error) {
	csvReader, fp, err := csvs.readerFunc(csvs.timingsFn, csvs.sep, getColumnCount(TpTiming{}))
	if err != nil {
		log.Print("Could not load timings file: ", err)
		// allow writing of the other values
		return nil, nil
	}
	if fp != nil {
		defer fp.Close()
	}
	var tpTimings []TpTiming
	for record, err := csvReader.Read(); err != io.EOF; record, err = csvReader.Read() {
		if err != nil {
			log.Print("bad line in timings csv: ", err)
			return nil, err
		}
		if tpTiming, err := csvLoad(TpTiming{}, record); err != nil {
			log.Print("error loading timing: ", err)
			return nil, err
		} else {
			tm := tpTiming.(TpTiming)
			tm.Tpid = tpid
			tpTimings = append(tpTimings, tm)
		}
	}
	return tpTimings, nil
}
コード例 #6
0
ファイル: storage_csv.go プロジェクト: nikbyte/cgrates
func (csvs *CSVStorage) GetTpLCRs(filter *TpLcrRule) ([]TpLcrRule, error) {
	csvReader, fp, err := csvs.readerFunc(csvs.lcrFn, csvs.sep, getColumnCount(TpLcrRule{}))
	if err != nil {
		log.Print("Could not load LCR rules file: ", err)
		// allow writing of the other values
		return nil, nil
	}
	if fp != nil {
		defer fp.Close()
	}
	var tpLCRs []TpLcrRule
	for record, err := csvReader.Read(); err != io.EOF; record, err = csvReader.Read() {
		if tpRate, err := csvLoad(TpLcrRule{}, record); err != nil {
			if err != nil {
				log.Print("bad line in lcr rules csv: ", err)
				return nil, err
			}
			return nil, err
		} else {
			lcr := tpRate.(TpLcrRule)
			if filter != nil {
				lcr.Tpid = filter.Tpid
			}
			tpLCRs = append(tpLCRs, lcr)
		}
	}
	return tpLCRs, nil
}
コード例 #7
0
ファイル: storage_csv.go プロジェクト: nikbyte/cgrates
func (csvs *CSVStorage) GetTpAccountActions(filter *TpAccountAction) ([]TpAccountAction, error) {
	csvReader, fp, err := csvs.readerFunc(csvs.accountactionsFn, csvs.sep, getColumnCount(TpAccountAction{}))
	if err != nil {
		log.Print("Could not load account actions file: ", err)
		// allow writing of the other values
		return nil, nil
	}
	if fp != nil {
		defer fp.Close()
	}
	var tpAccountActions []TpAccountAction
	for record, err := csvReader.Read(); err != io.EOF; record, err = csvReader.Read() {
		if err != nil {
			log.Print("bad line in account actions csv: ", err)
			return nil, err
		}
		if tpAa, err := csvLoad(TpAccountAction{}, record); err != nil {
			log.Print("error loading account action: ", err)
			return nil, err
		} else {
			aa := tpAa.(TpAccountAction)
			if filter != nil {
				aa.Tpid = filter.Tpid
				aa.Loadid = filter.Loadid
			}
			tpAccountActions = append(tpAccountActions, aa)
		}
	}
	return tpAccountActions, nil
}
コード例 #8
0
func handleClientRegister(httpReq *http.Request) (int, string) {
	//using authentication struct for now because i haven't added the token yet
	var req request.Authentication
	decoder := json.NewDecoder(httpReq.Body)
	err := decoder.Decode(&req)
	if err != nil {
		fmt.Println("error decoding register account request (authentication)")
		return 500, "Internal Server Error"
	}

	var username string
	var password string

	username, password, err = sanitize(req.Username, req.Password)
	if err != nil {
		log.Print("Error sanitizing authentication request", req.Username, req.Password)
		return 400, "Bad Request"
	}

	uid, err := thordb.RegisterAccount(username, password)
	if err != nil {
		log.Print(err)
		switch err.Error() {
		case "thordb: already in use":
			return 400, "Bad Request"
		default:
			return 500, "Internal Server Error"
		}
	}

	log.Print("thordb: registered player (", uid, ")")
	return 200, fmt.Sprintf("UserId%s", strconv.Itoa(uid))
}
コード例 #9
0
func handleCreateCharacter(httpReq *http.Request) (int, string) {
	var req request.CreateCharacter
	decoder := json.NewDecoder(httpReq.Body)
	err := decoder.Decode(&req)
	if err != nil {
		log.Print("character create req json decoding error %s", httpReq.Body)
		return 400, "Bad Request"
	}

	character := thordb.NewCharacterData()
	character.Name = req.Name

	var characterSession *thordb.CharacterSession
	characterSession, err = thordb.CreateCharacter(req.AccountToken, character)
	if err != nil {
		log.Print(err)
		switch err.Error() {
		case "thordb: already in use":
			return 400, "Bad Request"
		case "token contains an invalid number of segments":
			return 400, "Bad Request"
		default:
			return 500, "Internal Server Error"
		}
	}
	var jsonBytes []byte
	jsonBytes, err = json.Marshal(characterSession.CharacterData)
	if err != nil {
		log.Print(err)
		return 500, "Internal Server Error"
	}
	log.Printf("thordb: created character %d - %s\ncharacter details:\n%s", characterSession.ID, characterSession.Name, string(jsonBytes))
	return 200, characterSession.Token
}
コード例 #10
0
ファイル: mysql.go プロジェクト: strogo/GoMySQL
/**
 * Close the connection to the server
 */
func (mysql *MySQL) Close() (err os.Error) {
	if mysql.Logging {
		log.Print("Close called")
	}
	// If not connected return
	if !mysql.connected {
		err = os.NewError("A connection to a MySQL server is required to use this function")
		return
	}
	// Lock mutex and defer unlock
	mysql.mutex.Lock()
	defer mysql.mutex.Unlock()
	// Reset error/sequence vars
	mysql.reset()
	// Send quit command
	err = mysql.command(COM_QUIT, "")
	if err != nil {
		return
	}
	if mysql.Logging {
		log.Print("[" + fmt.Sprint(mysql.sequence-1) + "] " + "Sent quit command to server")
	}
	// Close connection
	mysql.conn.Close()
	mysql.connected = false
	if mysql.Logging {
		log.Print("Closed connection to server")
	}
	return
}
コード例 #11
0
ファイル: mysql.go プロジェクト: strogo/GoMySQL
/**
 * Ping server
 */
func (mysql *MySQL) Ping() (err os.Error) {
	if mysql.Logging {
		log.Print("Ping called")
	}
	// If not connected return
	if !mysql.connected {
		err = os.NewError("A connection to a MySQL server is required to use this function")
		return
	}
	// Lock mutex and defer unlock
	mysql.mutex.Lock()
	defer mysql.mutex.Unlock()
	// Reset error/sequence vars
	mysql.reset()
	// Send command
	err = mysql.command(COM_PING)
	if err != nil {
		return
	}
	if mysql.Logging {
		log.Print("[" + fmt.Sprint(mysql.sequence-1) + "] " + "Sent ping command to server")
	}
	// Get result packet
	err = mysql.getResult()
	return
}
コード例 #12
0
ファイル: camweb.go プロジェクト: robryk/camlistore
func mainHandler(rw http.ResponseWriter, req *http.Request) {
	relPath := req.URL.Path[1:] // serveFile URL paths start with '/'
	if strings.Contains(relPath, "..") {
		return
	}

	if strings.HasPrefix(relPath, "gw/") {
		path := relPath[3:]
		http.Redirect(rw, req, "http://camlistore.org/code/?p=camlistore.git;f="+path+";hb=master", http.StatusFound)
		return
	}

	absPath := filepath.Join(*root, "content", relPath)
	fi, err := os.Lstat(absPath)
	if err != nil {
		log.Print(err)
		serveError(rw, req, relPath, err)
		return
	}
	if fi.IsDir() {
		relPath += "/index.html"
		absPath = filepath.Join(*root, "content", relPath)
		fi, err = os.Lstat(absPath)
		if err != nil {
			log.Print(err)
			serveError(rw, req, relPath, err)
			return
		}
	}

	switch {
	case !fi.IsDir():
		serveFile(rw, req, relPath, absPath)
	}
}
コード例 #13
0
ファイル: binarylistener.go プロジェクト: trendrr/goshire
func handleConnection(conn *BinaryWriter) {
	defer conn.conn.Close()
	// log.Print("CONNECT!")

	decoder := BIN.NewDecoder(bufio.NewReader(conn.conn))
	_, err := decoder.DecodeHello()
	if err != nil {
		log.Print(err)
		return
	}
	for {
		req, err := decoder.DecodeRequest()
		if err == io.EOF {
			log.Print(err)
			break
		} else if err != nil {
			log.Print(err)
			break
		}
		// log.Printf("GOT REQUEST %s", req)
		// //request
		controller := conn.serverConfig.Router.Match(req.Method(), req.Uri())
		go HandleRequest(req, conn, controller, conn.serverConfig)
	}

	log.Print("DISCONNECT!")
}
コード例 #14
0
ファイル: servermanager.go プロジェクト: gtalent/dospin
func (me *ServerManager) setupListener(port int) {
	portStr := strconv.Itoa(port)
	addr, err := net.ResolveTCPAddr("tcp", "0.0.0.0:"+portStr)
	if err != nil {
		log.Print("Could not resolve port and listen address:", err)
		return
	}

	// listen on port
	go func() {
		l, err := net.ListenTCP("tcp", addr)
		if err != nil {
			log.Print("Could not listen for TCP connection:", err)
		} else {
			for {
				conn, err := l.AcceptTCP()
				if err != nil {
					log.Print("Could not accept TCP connection:", err)
				} else {
					// connection accepted

					// spinup machine
					me.Spinup()

					// close existing connection, not doing anything with it
					conn.Close()
				}
			}
		}
	}()
}
コード例 #15
0
ファイル: storage_csv.go プロジェクト: nikbyte/cgrates
func (csvs *CSVStorage) GetTpRatingProfiles(filter *TpRatingProfile) ([]TpRatingProfile, error) {
	csvReader, fp, err := csvs.readerFunc(csvs.ratingprofilesFn, csvs.sep, getColumnCount(TpRatingProfile{}))
	if err != nil {
		log.Print("Could not load rating profiles file: ", err)
		// allow writing of the other values
		return nil, nil
	}
	if fp != nil {
		defer fp.Close()
	}
	var tpRatingProfiles []TpRatingProfile
	for record, err := csvReader.Read(); err != io.EOF; record, err = csvReader.Read() {
		if err != nil {
			log.Print("bad line rating profiles csv: ", err)
			return nil, err
		}
		if tpRate, err := csvLoad(TpRatingProfile{}, record); err != nil {
			log.Print("error loading rating profile: ", err)
			return nil, err
		} else {
			rpf := tpRate.(TpRatingProfile)
			if filter != nil {
				rpf.Tpid = filter.Tpid
				rpf.Loadid = filter.Loadid
			}
			tpRatingProfiles = append(tpRatingProfiles, rpf)
		}
	}
	return tpRatingProfiles, nil
}
コード例 #16
0
ファイル: container.go プロジェクト: hsolomon/docker
func (container *Container) Stop(seconds int) error {
	container.State.Lock()
	defer container.State.Unlock()
	if !container.State.Running {
		return nil
	}

	// 1. Send a SIGTERM
	if output, err := exec.Command("lxc-kill", "-n", container.ID, "15").CombinedOutput(); err != nil {
		log.Print(string(output))
		log.Print("Failed to send SIGTERM to the process, force killing")
		if err := container.kill(); err != nil {
			return err
		}
	}

	// 2. Wait for the process to exit on its own
	if err := container.WaitTimeout(time.Duration(seconds) * time.Second); err != nil {
		log.Printf("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds)
		if err := container.kill(); err != nil {
			return err
		}
	}
	return nil
}
コード例 #17
0
ファイル: storage_csv.go プロジェクト: nikbyte/cgrates
func (csvs *CSVStorage) GetTpSharedGroups(tpid, tag string) ([]TpSharedGroup, error) {
	csvReader, fp, err := csvs.readerFunc(csvs.sharedgroupsFn, csvs.sep, getColumnCount(TpSharedGroup{}))
	if err != nil {
		log.Print("Could not load shared groups file: ", err)
		// allow writing of the other values
		return nil, nil
	}
	if fp != nil {
		defer fp.Close()
	}

	var tpSharedGroups []TpSharedGroup
	for record, err := csvReader.Read(); err != io.EOF; record, err = csvReader.Read() {
		if err != nil {
			log.Print("bad line in shared groups csv: ", err)
			return nil, err
		}
		if tpRate, err := csvLoad(TpSharedGroup{}, record); err != nil {
			log.Print("error loading shared group: ", err)
			return nil, err
		} else {
			sg := tpRate.(TpSharedGroup)
			sg.Tpid = tpid
			tpSharedGroups = append(tpSharedGroups, sg)
		}
	}
	return tpSharedGroups, nil
}
コード例 #18
0
ファイル: video_fetcher.go プロジェクト: unixpickle/chatsaver
func main() {
	if len(os.Args) != 3 {
		log.Fatal("Usage: image_fetcher <processed.js> <output>")
	}
	parsed, err := readProcessedData(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	dirPath := os.Args[2]
	for _, message := range parsed {
		if !message.HasAttachment {
			continue
		}
		for _, attachment := range message.Attachments {
			if attachment.Type != "video" {
				continue
			}
			data, err := downloadURL(attachment.URL)
			if err != nil {
				log.Print("error downloading file:", err)
			}
			u, err := url.Parse(attachment.URL)
			filename := path.Base(u.Path)
			downloadedPath := filepath.Join(dirPath, strconv.FormatInt(message.Timestamp, 10)+"_"+
				filename)
			if err := ioutil.WriteFile(downloadedPath, data, 0777); err != nil {
				log.Print("error writing file:", downloadedPath, ":", err)
			}
		}
	}
}
コード例 #19
0
ファイル: storage_csv.go プロジェクト: nikbyte/cgrates
func (csvs *CSVStorage) GetTpActionTriggers(tpid, tag string) ([]TpActionTrigger, error) {
	csvReader, fp, err := csvs.readerFunc(csvs.actiontriggersFn, csvs.sep, getColumnCount(TpActionTrigger{}))
	if err != nil {
		log.Print("Could not load action triggers file: ", err)
		// allow writing of the other values
		return nil, nil
	}
	if fp != nil {
		defer fp.Close()
	}
	var tpActionTriggers []TpActionTrigger
	for record, err := csvReader.Read(); err != io.EOF; record, err = csvReader.Read() {
		if err != nil {
			log.Print("bad line in action triggers csv: ", err)
			return nil, err
		}
		if tpAt, err := csvLoad(TpActionTrigger{}, record); err != nil {
			log.Print("error loading action trigger: ", err)
			return nil, err
		} else {
			at := tpAt.(TpActionTrigger)
			at.Tpid = tpid
			tpActionTriggers = append(tpActionTriggers, at)
		}
	}
	return tpActionTriggers, nil
}
コード例 #20
0
ファイル: store_darwin.go プロジェクト: jeisc/sneakynote.com
func teardownRamDisk(path string) error {
	out, err := exec.Command("hdiutil", "detach", "-force", path).CombinedOutput()
	if err != nil {
		// Sometimes there's a resource-busy error...sleep and retry
		time.Sleep(time.Second)
		out, err = exec.Command("hdiutil", "detach", "-force", path).CombinedOutput()
	}
	if err != nil {
		log.Print("Umounting/ejecting ramdisk: ", err, " ", string(out))
		return err
	}
	log.Printf("Ramdisk %s unmounted and ejected.", path)

	// rm -r is dangerous...
	if isMatch, _ := regexp.MatchString("\\A/tmp/[^/]+", path); isMatch {
		out, err = exec.Command("rm", "-r", path).CombinedOutput()
		// if err != nil {
		//   // Sometimes there's an error
		//   time.Sleep(time.Second)
		//   err = exec.Command("rm", "-r", path).Run()
		if err != nil {
			log.Print("rm -r: ", err, " ", string(out))
			return err
		}
		// }
		log.Printf("Mountpoint folder %s removed.", path)
	}

	return nil
}
コード例 #21
0
ファイル: storage_csv.go プロジェクト: nikbyte/cgrates
func (csvs *CSVStorage) GetTpDerivedChargers(filter *TpDerivedCharger) ([]TpDerivedCharger, error) {
	csvReader, fp, err := csvs.readerFunc(csvs.derivedChargersFn, csvs.sep, getColumnCount(TpDerivedCharger{}))
	if err != nil {
		log.Print("Could not load derivedChargers file: ", err)
		// allow writing of the other values
		return nil, nil
	}
	if fp != nil {
		defer fp.Close()
	}
	var tpDerivedChargers []TpDerivedCharger
	for record, err := csvReader.Read(); err != io.EOF; record, err = csvReader.Read() {
		if err != nil {
			log.Print("bad line in derived chargers csv: ", err)
			return nil, err
		}
		if tpRate, err := csvLoad(TpDerivedCharger{}, record); err != nil {
			log.Print("error loading derived charger: ", err)
			return nil, err
		} else {
			dc := tpRate.(TpDerivedCharger)
			if filter != nil {
				dc.Tpid = filter.Tpid
				dc.Loadid = filter.Loadid
			}
			tpDerivedChargers = append(tpDerivedChargers, dc)
		}
	}
	return tpDerivedChargers, nil
}
コード例 #22
0
ファイル: store_darwin.go プロジェクト: jeisc/sneakynote.com
func (s *Store) freeSpace() (int, error) {
	// On Linux with ramfs, just use free system memory minus a threshold
	// On Mac OS X we can read straigh out of the store
	df, err := exec.Command("df", s.Root).CombinedOutput()
	if err != nil {
		log.Print("Error getting store free space: ", err, string(df))
		return -1, err
	}
	// log.Print(string(df))
	// Filesystem 512-blocks Used Available Capacity iused ifree %iused  Mounted on
	// /dev/disk3       2048  288      1760    15%      34   220   13%   /private/tmp/hello

	regexp, err := regexp.Compile("\\s\\d+\\s")
	if err != nil {
		log.Print("Error compiling regexp: ", err)
		return -1, err
	}
	matches := regexp.FindAll(df, -1)
	if matches == nil {
		log.Print("Error matching df output")
		return -1, err
	}

	freeBlocksStr := strings.TrimSpace(string(matches[2]))
	freeBlocks, err := strconv.ParseInt(freeBlocksStr, 10, 64)
	if err != nil {
		log.Print("Error parsing freeBlocks string: ", err)
		return -1, err
	}
	// log.Print(free * 512)

	return int(freeBlocks) * 512, nil
}
コード例 #23
0
ファイル: storage_csv.go プロジェクト: nikbyte/cgrates
func (csvs *CSVStorage) GetTpAliases(filter *TpAlias) ([]TpAlias, error) {
	csvReader, fp, err := csvs.readerFunc(csvs.aliasesFn, csvs.sep, getColumnCount(TpAlias{}))
	if err != nil {
		log.Print("Could not load aliases file: ", err)
		// allow writing of the other values
		return nil, nil
	}
	if fp != nil {
		defer fp.Close()
	}
	var tpAliases []TpAlias
	for record, err := csvReader.Read(); err != io.EOF; record, err = csvReader.Read() {
		if err != nil {
			log.Print("bad line in aliases csv: ", err)
			return nil, err
		}
		if tpAlias, err := csvLoad(TpAlias{}, record); err != nil {
			log.Print("error loading alias: ", err)
			return nil, err
		} else {
			u := tpAlias.(TpAlias)
			if filter != nil {
				u.Tpid = filter.Tpid
			}
			tpAliases = append(tpAliases, u)
		}
	}
	return tpAliases, nil
}
コード例 #24
0
ファイル: italic.go プロジェクト: oneplus1000/gopdfsample
//gopdf had no mechanism for set italic ( pdf.SetFont("SOMEFONT", "I", 14) ), but you can do like this.
func main() {
	pdf := gopdf.GoPdf{}
	pdf.Start(gopdf.Config{Unit: "pt", PageSize: gopdf.Rect{W: 595.28, H: 841.89}}) //595.28, 841.89 = A4
	pdf.AddPage()

	err := pdf.AddTTFFont("DejaVuSerif", "../ttf/DejaVuSerif.ttf")
	if err != nil {
		log.Print(err.Error())
		return
	}
	err = pdf.AddTTFFont("DejaVuSerif-Italic", "../ttf/DejaVuSerif-Italic.ttf")
	if err != nil {
		log.Print(err.Error())
		return
	}

	err = pdf.SetFont("DejaVuSerif", "", 14)
	if err != nil {
		log.Print(err.Error())
		return
	}
	pdf.Cell(nil, "Hi! This is nomal.")
	pdf.Br(20)

	err = pdf.SetFont("DejaVuSerif-Italic", "", 14)
	if err != nil {
		log.Print(err.Error())
		return
	}
	pdf.Cell(nil, "Hi! This is italic.")
	pdf.WritePdf("italic.pdf")
}
コード例 #25
0
ファイル: storage_csv.go プロジェクト: nikbyte/cgrates
func (csvs *CSVStorage) GetTpDestinations(tpid, tag string) ([]TpDestination, error) {
	csvReader, fp, err := csvs.readerFunc(csvs.destinationsFn, csvs.sep, getColumnCount(TpDestination{}))
	if err != nil {
		log.Print("Could not load destinations file: ", err)
		// allow writing of the other values
		return nil, nil
	}
	if fp != nil {
		defer fp.Close()
	}
	var tpDests []TpDestination
	for record, err := csvReader.Read(); err != io.EOF; record, err = csvReader.Read() {
		if err != nil {
			log.Print("bad line in destinations csv: ", err)
			return nil, err
		}
		if tpDest, err := csvLoad(TpDestination{}, record); err != nil {
			log.Print("error loading destination: ", err)
			return nil, err
		} else {
			d := tpDest.(TpDestination)
			d.Tpid = tpid
			tpDests = append(tpDests, d)
		}
	}
	return tpDests, nil
}
コード例 #26
0
ファイル: storage_csv.go プロジェクト: nikbyte/cgrates
func (csvs *CSVStorage) GetTpDestinationRates(tpid, tag string, p *utils.Paginator) ([]TpDestinationRate, error) {
	csvReader, fp, err := csvs.readerFunc(csvs.destinationratesFn, csvs.sep, getColumnCount(TpDestinationRate{}))
	if err != nil {
		log.Print("Could not load destination_rates file: ", err)
		// allow writing of the other values
		return nil, nil
	}
	if fp != nil {
		defer fp.Close()
	}
	var tpDestinationRates []TpDestinationRate
	for record, err := csvReader.Read(); err != io.EOF; record, err = csvReader.Read() {
		if err != nil {
			log.Print("bad line in destinationrates csv: ", err)
			return nil, err
		}
		if tpRate, err := csvLoad(TpDestinationRate{}, record); err != nil {
			log.Print("error loading destination rate: ", err)
			return nil, err
		} else {
			dr := tpRate.(TpDestinationRate)
			dr.Tpid = tpid
			tpDestinationRates = append(tpDestinationRates, dr)
		}
	}
	return tpDestinationRates, nil
}
コード例 #27
0
ファイル: proc.go プロジェクト: janhelke/sys-file-indexer
// Slower operations to fill props struct
func (p *props) load(h hash.Hash, name string) *props {
	p.mime = mime.TypeByExtension(p.ext)
	r, err := os.Open(name)
	if err != nil {
		log.Print(name, ": Props: ", err)
		return p
	}
	defer r.Close()
	p.ftype = mapType(p.mime)
	// TODO: this is quite unreadable
	copy(p.chash[:], filehash(name, h, r))
	copy(p.dident[:], strhash(p.dir, h))
	// If the extension is empty, we need to detect
	// the MIME type via file contents
	if p.mime == "" {
		p.mime = sniffMIME(name, r)
	}
	// Non-images are completely processed at this point
	if !strings.HasPrefix(p.mime, "image/") {
		return p
	}
	// Image-specific processing
	if _, err := r.Seek(0, 0); err != nil {
		log.Print(name, ": Seek: ", err)
		return p
	}
	imgconf, _, err := image.DecodeConfig(r)
	if err != nil {
		log.Print(name, ": Image decoder: ", err)
		return p
	}
	p.isize = image.Point{imgconf.Width, imgconf.Height}
	return p
}
コード例 #28
0
ファイル: storage_csv.go プロジェクト: nikbyte/cgrates
func (csvs *CSVStorage) GetTpRatingPlans(tpid, tag string, p *utils.Paginator) ([]TpRatingPlan, error) {
	csvReader, fp, err := csvs.readerFunc(csvs.destinationratetimingsFn, csvs.sep, getColumnCount(TpRatingPlan{}))
	if err != nil {
		log.Print("Could not load rate plans file: ", err)
		// allow writing of the other values
		return nil, nil
	}
	if fp != nil {
		defer fp.Close()
	}
	var tpRatingPlans []TpRatingPlan
	for record, err := csvReader.Read(); err != io.EOF; record, err = csvReader.Read() {
		if err != nil {
			log.Print("bad line in rating plans csv: ", err)
			return nil, err
		}
		if tpRate, err := csvLoad(TpRatingPlan{}, record); err != nil {
			log.Print("error loading rating plan: ", err)
			return nil, err
		} else {
			rp := tpRate.(TpRatingPlan)
			rp.Tpid = tpid
			tpRatingPlans = append(tpRatingPlans, rp)
		}
	}
	return tpRatingPlans, nil
}
コード例 #29
0
ファイル: pownyapp-backend.go プロジェクト: dmage/pieceofapp
func (s *Server) sendPushNotification(login string) {
	token, err := s.getIOSToken(login)
	if err != nil {
		log.Print("Failed to get token for ", login, ": ", err)
		return
	}

	p := apns.NewPayload()
	//p.APS.Alert.Body = "Received a new message."
	//badge := 1
	//p.APS.Badge = &badge
	//p.APS.Sound = "1"
	p.APS.Sound = ""
	p.APS.ContentAvailable = 1

	m := apns.NewNotification()
	m.Payload = p
	m.DeviceToken = token
	m.Priority = apns.PriorityImmediate
	//m.Identifier = 12312, // Integer for APNS
	//m.ID = "user_id:timestamp", // ID not sent to Apple – to identify error notifications

	err = s.apnsClient.Send(m)
	log.Print("sent push for ", login, ": ", err)
}
コード例 #30
0
ファイル: search_server.go プロジェクト: noah-wung/wukong
/*******************************************************************************
	主函数
*******************************************************************************/
func main() {
	// 解析命令行参数
	flag.Parse()

	// 初始化
	gob.Register(WeiboScoringFields{})
	searcher.Init(types.EngineInitOptions{
		SegmenterDictionaries: "../../data/dictionary.txt",
		StopTokenFile:         "../../data/stop_tokens.txt",
		IndexerInitOptions: &types.IndexerInitOptions{
			IndexType: types.LocationsIndex,
		},
	})
	wbs = make(map[uint64]Weibo)

	// 索引
	go indexWeibo()

	// 捕获ctrl-c
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		for _ = range c {
			log.Print("捕获Ctrl-c,退出服务器")
			searcher.Close()
			os.Exit(0)
		}
	}()

	http.HandleFunc("/json", JsonRpcServer)
	http.Handle("/", http.FileServer(http.Dir("static")))
	log.Print("服务器启动")
	http.ListenAndServe(":8080", nil)
}