Esempio n. 1
0
func main() {
	flag.Parse()
	var handle *pcap.Handle
	var err error
	if *fname != "" {
		if handle, err = pcap.OpenOffline(*fname); err != nil {
			log.Fatalln("PCAP OpenOffline error:", err)
		}
	} else {
		if handle, err = pcap.OpenLive(*iface, int32(*snaplen), true, time.Second); err != nil {
			log.Fatalln("PCAP OpenLive error:", err)
		}
		if *tstype != "" {
			if t, err := pcap.TimestampSourceFromString(*tstype); err != nil {
				log.Fatalf("Supported timestamp types: %v", handle.SupportedTimestamps())
			} else if err := handle.SetTimestampSource(t); err != nil {
				log.Fatalf("Supported timestamp types: %v", handle.SupportedTimestamps())
			}
		}
		if len(flag.Args()) > 0 {
			bpffilter := strings.Join(flag.Args(), " ")
			fmt.Fprintf(os.Stderr, "Using BPF filter %q\n", bpffilter)
			if err = handle.SetBPFFilter(bpffilter); err != nil {
				log.Fatalln("BPF filter error:", err)
			}
		}
	}
	dumpcommand.Run(handle)
}
Esempio n. 2
0
func TestGetTeam(t *testing.T) {

	db, err := openDB()

	defer db.Close()

	team1 := steward.Team{
		ID: -1, Name: "MySuperTeam", Subnet: "192.168.111/24",
		Vulnbox: "pl.hold1", UseNetbox: false, Netbox: "nb.hold1"}

	team1.ID, _ = steward.AddTeam(db.db, team1)

	_team1, err := steward.GetTeam(db.db, team1.ID)
	if err != nil {
		log.Fatalln("Get team failed:", err)
	}

	if _team1 != team1 {
		log.Fatalln("Added team broken")
	}

	_, err = steward.GetTeam(db.db, 10) // invalid team id
	if err == nil {
		log.Fatalln("Get invalid team broken")
	}
}
Esempio n. 3
0
func TestProgressWriterIgnoreTotal(t *testing.T) {
	filename := "progress_test.go"
	f, err := os.Open(filename)
	defer f.Close()
	if err != nil {
		log.Fatalln(err)
	}
	fs, err := os.Stat(filename)
	if err != nil {
		log.Fatalln(err)
	}

	p := New()
	p.IgnoreTotal = true
	p.Progress = func(current, total, expected int64) {
		log.Println("Ignore total writing", current, total, expected)
		assert.Equal(t, true, current >= total)
	}

	b := new(bytes.Buffer)
	w := io.MultiWriter(p, b)
	_, err = io.Copy(w, f)
	if err != nil {
		log.Fatalln(err)
	}
	assert.Equal(t, fs.Size(), int64(b.Len()))
}
Esempio n. 4
0
File: main.go Progetto: qgweb/gopro
func init() {
	flag.Parse()

	if *conf == "" {
		log.Fatalln("配置文件不存在")
	}

	confData, err := ioutil.ReadFile(*conf)
	if err != nil {
		log.Fatalln("读取配置文件出错,错误信息为:", err)
	}

	IniFile, err = ini.Load(confData)
	if err != nil {
		log.Fatalln("生成配置文件结构出错,错误信息为:", err)
	}

	pool = GetRedisPool()

	//	httpclient = http.Client{
	//		Transport: &http.Transport{
	//			Dial: func(netw, addr string) (net.Conn, error) {
	//				deadline := time.Now().Add(25 * time.Second)
	//				c, err := net.DialTimeout(netw, addr, time.Second*20)
	//				if err != nil {
	//					return nil, err
	//				}
	//				c.SetDeadline(deadline)
	//				return c, nil
	//			},
	//			DisableKeepAlives: true,
	//		},
	//	}
}
Esempio n. 5
0
func main() {
	flag.Parse()
	file := flag.Arg(0)

	io, err := os.Open(file)
	if err != nil {
		log.Fatalln("Can't open file: ", file)
	}

	img, err := jpeg.Decode(io, &jpeg.DecoderOptions{})
	if img == nil {
		log.Fatalln("Got nil")
	}
	if err != nil {
		log.Fatalln("Got Error: %v", err)
	}

	//
	// write your code here ...
	//

	switch img.(type) {
	case *image.YCbCr:
		log.Println("decoded YCbCr")
	case *image.Gray:
		log.Println("decoded Gray")
	default:
		log.Println("unknown format")
	}
}
Esempio n. 6
0
func main() {
	err := graphics.Init()
	if err != nil {
		log.Fatalln(err)
	}
	defer graphics.Quit()

	win, err := graphics.CreateWindow(800, 600, "Test")
	if err != nil {
		log.Fatalln(err)
	}
	defer win.Destroy()

	if len(os.Args) == 1 {
		newBackEnd()
	}

	frontend := NewPlayerFrontend(win)

	if len(os.Args) == 1 {
		joinEvent := &events.PlayerJoin{
			UUID: frontend.id,
		}
		events.SendEvent(joinEvent)

		go StartNetworkListener()
		loadlevel := events.LoadLevel{
			FileName: "assets/testTiles.json",
		}
		events.SendEvent(&loadlevel)
	} else {
		NewNetworkBackend(os.Args[1])
	}
	frontend.Mainloop()
}
Esempio n. 7
0
func main() {
	var file *os.File
	var err error

	if file, err = os.Open("files/sample.tar.bz2"); err != nil {
		log.Fatalln(err)
	}
	defer file.Close()

	reader := tar.NewReader(bzip2.NewReader(file))

	var header *tar.Header
	for {
		header, err = reader.Next()
		if err == io.EOF {
			// ファイルの最後
			break
		}
		if err != nil {
			log.Fatalln(err)
		}

		buf := new(bytes.Buffer)
		if _, err = io.Copy(buf, reader); err != nil {
			log.Fatalln(err)
		}

		if err = ioutil.WriteFile("output/"+header.Name, buf.Bytes(), 0755); err != nil {
			log.Fatal(err)
		}
	}
}
Esempio n. 8
0
func viewInvite(w http.ResponseWriter, r *http.Request) {
	mail := r.PostFormValue("mail")
	conf, err := loadConf()
	if err != nil {
		log.Fatalln(err)
	}

	client := &http.Client{}
	data := url.Values{
		"email":      {mail},
		"token":      {conf.Token},
		"set_active": {"true"},
	}

	resp, err := client.Post(
		"https://"+conf.URL+"/api/users.admin.invite",
		"application/x-www-form-urlencoded",
		strings.NewReader(data.Encode()),
	)
	if err != nil {
		log.Fatalln(err)
	}
	body, _ := ioutil.ReadAll(resp.Body)

	var status map[string]interface{}
	json.Unmarshal(body, &status)
	fmt.Println(status["ok"])
	statusOk := fmt.Sprint(status["ok"])

	if statusOk == "true" {
		fmt.Fprintf(w, mail+"に招待状を送信しました.")
	} else {
		fmt.Fprintf(w, "失敗した。失敗した。失敗した。"+fmt.Sprint(status["error"]))
	}
}
Esempio n. 9
0
func main() {
	tpl, err := template.ParseGlob("templates/*.gmao")
	if err != nil {
		log.Fatalln(err)
	}

	err = tpl.Execute(os.Stdout, nil)
	if err != nil {
		log.Fatalln(err)
	}

	err = tpl.ExecuteTemplate(os.Stdout, "vespa.gmao", nil)
	if err != nil {
		log.Fatalln(err)
	}

	err = tpl.ExecuteTemplate(os.Stdout, "two.gmao", nil)
	if err != nil {
		log.Fatalln(err)
	}

	err = tpl.ExecuteTemplate(os.Stdout, "one.gmao", nil)
	if err != nil {
		log.Fatalln(err)
	}
}
Esempio n. 10
0
func (publ *Publisher) run() {
	sock, err := pub.NewSocket()
	if err != nil {
		log.Fatalln("pub.NewSocket error:", err)
	}
	sock.AddTransport(inproc.NewTransport())
	sock.AddTransport(tcp.NewTransport())
	defer sock.Close()
	if publ.Connect {
		err = sock.Dial(publ.Endpoint)
	} else {
		err = sock.Listen(publ.Endpoint)
	}
	if err != nil {
		log.Fatalln("sock connect failed:", err)
	}

	// sending on a socket straight away silently fails, so wait 20ms. ugh.
	time.Sleep(time.Millisecond * 20)

	for ev := range publ.Channel {
		// format: topic\0data
		data := fmt.Sprintf("%s\000%s", ev.Topic, ev.String())
		err := sock.Send([]byte(data))
		if err != nil {
			log.Fatalln("Failed to Send message:", err)
		}
	}
}
Esempio n. 11
0
func main() {
	src, err := os.Open("table.csv")
	if err != nil {
		log.Fatalln("error opening table.csv:", err)
	}
	defer src.Close()

	dst, err := os.Create("table.json")
	if err != nil {
		log.Fatalln("error opening table.csv:", err)
	}
	defer dst.Close()

	rdr := csv.NewReader(src)
	rows, err := rdr.ReadAll()
	if err != nil {
		log.Fatalln("error reading file:", err)
	}

	records := make([]record, len(rows))
	for _, row := range rows[1:] {
		records = append(records, makeRecord(row))
	}

	err = json.NewEncoder(dst).Encode(records)
	if err != nil {
		log.Fatalln("error encoding to json:", err)
	}
}
Esempio n. 12
0
func getUsers(db *sql.DB) []User {
	q := `
		SELECT
			ID, Name, Phone, Created
		FROM
			users
		ORDER BY datetime(Created) DESC
	`

	rows, err := db.Query(q)
	if err != nil {
		log.Fatalln(err)
	}
	defer rows.Close()

	var users []User
	for rows.Next() {
		user := User{}
		err = rows.Scan(&user.ID, &user.Name, &user.Phone, &user.Created)
		if err != nil {
			log.Fatalln(err)
		}
		users = append(users, user)
	}
	return users
}
// BenchmarkPreparedStatementsSingle is the case that the user creates a single prepared statement uses it reuses it
func BenchmarkPreparedStatementsSingle(b *testing.B) {
	conn := mysqlConn()
	b.ResetTimer()

	stmt, err := conn.Prepare("select id, subject, state from tickets where subdomain_id = ? and (state = ? or state = ?) limit 1")
	if err != nil {
		log.Fatalln(err)
	}
	for n := 0; n < b.N; n++ {
		rows, err := stmt.Query(1, "open", "spam")
		if err != nil {
			log.Fatalln(err)
		}

		var id int
		var subject string
		var state string
		for rows.Next() {
			err := rows.Scan(&id, &subject, &state)
			if err != nil {
				log.Fatalln(err)
			}
		}

		rows.Close()
	}

	conn.Close()
}
Esempio n. 14
0
File: cfg.go Progetto: donh/agent
func ParseConfig(cfg string) {
	if cfg == "" {
		log.Fatalln("use -c to specify configuration file")
	}

	if !file.IsExist(cfg) {
		log.Fatalln("config file:", cfg, "is not existent. maybe you need `mv cfg.example.json cfg.json`")
	}

	ConfigFile = cfg

	configContent, err := file.ToTrimString(cfg)
	if err != nil {
		log.Fatalln("read config file:", cfg, "fail:", err)
	}

	var c GlobalConfig
	err = json.Unmarshal([]byte(configContent), &c)
	if err != nil {
		log.Fatalln("parse config file:", cfg, "fail:", err)
	}

	lock.Lock()
	defer lock.Unlock()

	config = &c

	log.Println("read config file:", cfg, "successfully")
}
Esempio n. 15
0
// Listen creates a UDP server that parses statsd data into metrics and
// sends them over a channel.
func Listen(addr string, c chan Packet, clean bool) {
	cleaner := NewCleaner()
	laddr, err := net.ResolveUDPAddr("udp", addr)
	if err != nil {
		log.Fatalln("fatal: failed to resolve address", err)
	}
	conn, err := net.ListenUDP("udp", laddr)
	if err != nil {
		log.Fatalln("fatal: failed to listen", err)
	}
	for {
		buf := make([]byte, 1452)
		n, raddr, err := conn.ReadFrom(buf[:])
		t := time.Now().UTC()
		if err != nil {
			log.Println("error: Failed to recieve packet", err)
		} else {
			metrics, err := Parse(buf[0:n])
			if err != nil {
				log.Println("error: Failed to recieve packet", err)
			}
			if metrics != nil {
				var p Packet
				if clean {
					cleaned := cleaner.CleanMetrics(*metrics)
					p = Packet{&cleaned, raddr, t}
				} else {
					p = Packet{metrics, raddr, t}
				}

				c <- p
			}
		}
	}
}
Esempio n. 16
0
func initDb() *gorp.DbMap {
	// Delete our SQLite database if it already exists so we have a clean start
	_, err := os.Open("martini-sessionauth.bin")
	if err == nil {
		os.Remove("martini-sessionauth.bin")
	}

	db, err := sql.Open("sqlite3", "martini-sessionauth.bin")
	if err != nil {
		log.Fatalln("Fail to create database", err)
	}

	dbmap := &gorp.DbMap{Db: db, Dialect: gorp.SqliteDialect{}}
	dbmap.AddTableWithName(MyUserModel{}, "users").SetKeys(true, "Id")
	err = dbmap.CreateTablesIfNotExists()
	if err != nil {
		log.Fatalln("Could not build tables", err)
	}

	user := MyUserModel{1, "testuser", "password", false}
	err = dbmap.Insert(&user)
	if err != nil {
		log.Fatalln("Could not insert test user", err)
	}
	return dbmap
}
Esempio n. 17
0
func main() {
	tpl, err := template.ParseFiles("index.html")
	if err != nil {
		log.Fatalln(err)
	}
	http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
		data := foo(req.FormValue("name"), req.FormValue("age"))
		code := getCode(data)
		cookie, err := req.Cookie("session-fino")
		if err != nil {
			id, _ := uuid.NewV4()
			cookie = &http.Cookie{
				Name:  "session-fino",
				Value: id.String() + "|" + data + "|" + code,
				// Secure: true,
				HttpOnly: true,
			}
			http.SetCookie(res, cookie)
		}
		res.Header().Set("Content-Type", "text/html; charset=utf-8")
		xs := strings.Split(cookie.Value, "|")
		usrPics := xs[1] + "Different"
		usrCode := xs[2]
		if usrCode == getCode(usrPics) {
			fmt.Fprintf(res, "Code Valid\n")
		} else {
			fmt.Fprintf(res, "Code Invalid\n")
		}
		err = tpl.Execute(res, nil)
		if err != nil {
			log.Fatalln(err)
		}
	})
	http.ListenAndServe(":8080", nil)
}
Esempio n. 18
0
func main() {
	swaggerSpec, err := spec.New(SwaggerJSON, "")
	if err != nil {
		log.Fatalln(err)
	}

	parser := flags.NewParser(&opts, flags.Default)
	parser.ShortDescription = swaggerSpec.Spec().Info.Title
	parser.LongDescription = swaggerSpec.Spec().Info.Description

	if _, err := parser.Parse(); err != nil {
		os.Exit(1)
	}

	api := operations.NewTodoListAPI(swaggerSpec)
	handler := configureAPI(api)

	httpServer := &graceful.Server{Server: new(http.Server)}
	httpServer.Handler = handler

	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port))
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Printf("serving todo list at http://%s\n", listener.Addr())
	if err := httpServer.Serve(tcpKeepAliveListener{listener.(*net.TCPListener)}); err != nil {
		log.Fatalln(err)
	}

}
Esempio n. 19
0
func getFolders() []FolderConfiguration {
	Trace.Println("Getting Folders")
	r, err := http.NewRequest("GET", target+"/rest/system/config", nil)
	res, err := performRequest(r)
	defer func() {
		if res != nil && res.Body != nil {
			res.Body.Close()
		}
	}()
	if err != nil {
		log.Fatalln("Failed to perform request /rest/system/config: ", err)
	}
	if res.StatusCode != 200 {
		log.Fatalf("Status %d != 200 for GET /rest/system/config: ", res.StatusCode)
	}
	bs, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Fatalln(err)
	}
	var cfg Configuration
	err = json.Unmarshal(bs, &cfg)
	if err != nil {
		log.Fatalln(err)
	}
	return cfg.Folders
}
Esempio n. 20
0
func main() {

	if len(os.Args) != 2 {
		log.Fatalln("please specify a template to execute.")
	}

	path := os.Args[1]
	filename := filepath.Base(path)

	funcMap := template.FuncMap{
		"removenewlines": func(s string) string {
			return spaceRegex.ReplaceAllString(s, " ")
		},
		"statustext":    http.StatusText,
		"prettygorilla": prettyGorillaMuxPath,
	}

	tmpl := template.Must(template.New(filename).Funcs(funcMap).ParseFiles(path))

	data := struct {
		RouteDescriptors []v2.RouteDescriptor
		ErrorDescriptors []errcode.ErrorDescriptor
	}{
		RouteDescriptors: v2.APIDescriptor.RouteDescriptors,
		ErrorDescriptors: errcode.GetErrorCodeGroup("registry.api.v2"),
	}

	if err := tmpl.Execute(os.Stdout, data); err != nil {
		log.Fatalln(err)
	}
}
Esempio n. 21
0
func main() {
	// 0. get csv file - http://statetable.com/
	// 1. open and read csv file
	// 2. parse csv
	// 3. show results

	f, err := os.Open("../resources/state_table.csv")
	if err != nil {
		log.Fatalln("couldn't open csv file", err.Error())
	}

	myReader := csv.NewReader(f)

	records, err := myReader.ReadAll()
	if err != nil {
		log.Fatalln("couldn't read it!", err.Error())
	}

	// create a map for looking up values
	myStates := make(map[string]string)

	for _, value := range records {
		//		fmt.Println(key,"-",value)
		myStates[value[2]] = value[1]
	}

	for k, v := range myStates {
		fmt.Println(k, v)
	}
}
Esempio n. 22
0
func readonlyDB() *DB {
	numPrefixes := 100
	roDBOnce.Do(func() {
		var prefixes []*net.IPNet
		for _, l := range []int{8, 16, 24, 32} {
			b := l / 8
			for n := 0; n < numPrefixes; n++ {
				ip := make([]byte, 4)
				for i := 0; i < b; i++ {
					ip[i] = byte(rand.Int())
				}
				prefixes = append(prefixes, &net.IPNet{net.IP(ip), net.CIDRMask(l, 32)})
			}
		}

		db, err := New(":memory:")
		if err != nil {
			log.Fatalln(err)
		}

		r := db.Realm("prod")
		if err = r.Create(); err != nil {
			log.Fatalln(err)
		}

		for _, p := range prefixes {
			r.Prefix(p).Create()
		}
		roDB = db
	})
	return roDB
}
Esempio n. 23
0
func foo(res http.ResponseWriter, req *http.Request) {

	templ, error := template.ParseFiles("tpl.gohtml") // Parse template file
	if error != nil {
		log.Fatalln(error)
	}

	error = templ.Execute(os.Stdout, nil)
	if error != nil {
		log.Fatalln(error)
	}

	cookie, err := req.Cookie("session-fino")

	if err != nil {
		// id, _ := uuid.NewV4()
		cookie = &http.Cookie{
			Name:  "session-fino",
			Value: "0",
			// Secure: true,
			HttpOnly: true,
		}

	}
	count, _ := strconv.Atoi(cookie.Value)
	count++
	cookie.Value = strconv.Itoa(count)
	fmt.Println(cookie)

	http.SetCookie(res, cookie)

	templ.ExecuteTemplate(res, "tpl.gohtml", cookie)

}
Esempio n. 24
0
func genTypeRegistry(objects []Object, pkg string) {
	file := pkg + "/registry.go"

	fd, err := os.Create(file)
	if err != nil {
		log.Fatalln(err)
	}
	defer fd.Close()

	data := new(bytes.Buffer)
	data.WriteString("package " + pkg + "\n")

	tmpl := template.Must(template.New("registry").Parse(registryTmpl))
	err = tmpl.Execute(data, objects)
	if err != nil {
		log.Fatalln(err)
	}

	source := data.Bytes()
	fsource, err := format.Source(source)
	if err != nil {
		fd.Write(source)
		log.Fatalf("There are errors in the generated source for %s: %s\n", file, err.Error())
	}
	fd.Write(fsource)
}
Esempio n. 25
0
func TestGetTeams(t *testing.T) {

	db, err := openDB()

	defer db.Close()

	team1 := steward.Team{
		ID: -1, Name: "MySuperTeam", Subnet: "192.168.111/24",
		Vulnbox: "pl.hold1", UseNetbox: false, Netbox: "nb.hold1"}
	team2 := steward.Team{
		ID: -1, Name: "MyFooTeam", Subnet: "192.168.112/24",
		Vulnbox: "pl.hold2", UseNetbox: true, Netbox: "nb.hold2"}

	team1.ID, _ = steward.AddTeam(db.db, team1)
	team2.ID, _ = steward.AddTeam(db.db, team2)

	teams, err := steward.GetTeams(db.db)
	if err != nil {
		log.Fatalln("Get teams failed:", err)
	}

	if len(teams) != 2 {
		log.Fatalln("Get teams more than added")
	}

	if teams[0] != team1 || teams[1] != team2 {
		log.Fatalln("Added teams broken")
	}
}
Esempio n. 26
0
func main() {
	tpl, err := template.ParseFiles("user.html")
	if err != nil {
		log.Fatalln(err)
	}

	http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
		name := req.FormValue("name")
		age := req.FormValue("age")
		info := stuff(name, age)
		code := getCode(info)
		cookie, err := req.Cookie("session-fino")
		if err != nil {
			id, _ := uuid.NewV4()
			cookie = &http.Cookie{
				Name:  "session-fino",
				Value: id.String() + "|" + name + age + "|" + info + "|" + code,
				// Secure: true,
				HttpOnly: true,
			}
			http.SetCookie(res, cookie)

		}

		err = tpl.Execute(res, nil)
		if err != nil {
			log.Fatalln(err)
		}
	})

	http.ListenAndServe(":8080", nil)
}
Esempio n. 27
0
func main() {
	var opts struct {
		ClientID     string `long:"client_id"     required:"true"`
		ClientSecret string `long:"client_secret" required:"true"`
	}
	_, err := flags.Parse(&opts)
	if err != nil {
		log.Fatalln(err)
		return
	}

	config := &oauth2.Config{
		ClientID:     opts.ClientID,
		ClientSecret: opts.ClientSecret,
		RedirectURL:  "urn:ietf:wg:oauth:2.0:oob",
		Scopes:       []string{"https://www.googleapis.com/auth/gmail.send"},
		Endpoint: oauth2.Endpoint{
			AuthURL:  "https://accounts.google.com/o/oauth2/auth",
			TokenURL: "https://accounts.google.com/o/oauth2/token",
		},
	}

	var code string
	url := config.AuthCodeURL("")
	fmt.Println("ブラウザで以下のURLにアクセスし、認証してCodeを取得してください。")
	fmt.Println(url)
	fmt.Println("取得したCodeを入力してください")
	fmt.Scanf("%s\n", &code)
	token, err := config.Exchange(context.Background(), code)
	if err != nil {
		log.Fatalln("Exchange: ", err)
	}
	fmt.Println("RefreshToken: ", token.RefreshToken)
}
Esempio n. 28
0
func main() {
	defer util.Run()()
	var ring *pfring.Ring
	var err error
	if ring, err = pfring.NewRing(*iface, uint32(*snaplen), pfring.FlagPromisc); err != nil {
		log.Fatalln("pfring ring creation error:", err)
	}
	if len(flag.Args()) > 0 {
		bpffilter := strings.Join(flag.Args(), " ")
		fmt.Fprintf(os.Stderr, "Using BPF filter %q\n", bpffilter)
		if err = ring.SetBPFFilter(bpffilter); err != nil {
			log.Fatalln("BPF filter error:", err)
		}
	}
	if *cluster >= 0 {
		if err = ring.SetCluster(*cluster, pfring.ClusterType(*clustertype)); err != nil {
			log.Fatalln("pfring SetCluster error:", err)
		}
	}
	if err = ring.SetSocketMode(pfring.ReadOnly); err != nil {
		log.Fatalln("pfring SetSocketMode error:", err)
	} else if err = ring.Enable(); err != nil {
		log.Fatalln("pfring Enable error:", err)
	}
	dumpcommand.Run(ring)
}
Esempio n. 29
0
func TestProgressReader(t *testing.T) {
	filename := "progress_test.go"
	f, err := os.Open(filename)
	defer f.Close()
	if err != nil {
		log.Fatalln(err)
	}
	fs, err := os.Stat(filename)
	if err != nil {
		log.Fatalln(err)
	}

	p := New()
	p.Total = fs.Size()
	p.Progress = func(current, total, expected int64) {
		log.Println("Reading", current, total, expected)
		assert.Equal(t, true, current <= total)
	}

	b := new(bytes.Buffer)
	r := syncreader.New(f, p)
	_, err = b.ReadFrom(r)
	if err != nil {
		log.Fatalln(err)
	}
	assert.Equal(t, fs.Size(), int64(b.Len()))
}
Esempio n. 30
0
// 画一个带有text的图片
func drawStringImage(text string, fontFile string) image.Image {
	fontBytes, err := ioutil.ReadFile(fontFile)
	if err != nil {
		log.Fatalln(err)
	}

	font, err := freetype.ParseFont(fontBytes)
	if err != nil {
		log.Fatalln(err)
	}

	fg, bg := image.Black, image.White
	rgba := image.NewRGBA(image.Rect(0, 0, 640, 480))
	draw.Draw(rgba, rgba.Bounds(), bg, image.ZP, draw.Src)

	c := freetype.NewContext()
	c.SetDPI(72)
	c.SetFont(font)
	c.SetFontSize(12)
	c.SetClip(rgba.Bounds())
	c.SetDst(rgba)
	c.SetSrc(fg)

	// Draw the text.
	pt := freetype.Pt(10, 10+int(c.PointToFix32(12)>>8))
	for _, s := range strings.Split(text, "\r\n") {
		_, err = c.DrawString(s, pt)
		pt.Y += c.PointToFix32(12 * 1.5)
	}

	return rgba
}