Exemplo n.º 1
0
func (in *Input) Error(args ...interface{}) {
	if panicOnError {
		panic(fmt.Errorf("%s:%d: %s", in.File(), in.Line(), fmt.Sprintln(args...)))
	}
	fmt.Fprintf(os.Stderr, "%s:%d: %s", in.File(), in.Line(), fmt.Sprintln(args...))
	os.Exit(1)
}
Exemplo n.º 2
0
func (e *Engine) Start() {
	var err error

	e.shader.program, err = LoadProgram("shader.v.glsl", "shader.f.glsl")
	if err != nil {
		panic(fmt.Sprintln("LoadProgram failed:", err))
	}

	e.shape.buf = gl.CreateBuffer()
	gl.BindBuffer(gl.ARRAY_BUFFER, e.shape.buf)
	gl.BufferData(gl.ARRAY_BUFFER, EncodeObject(cubeData), gl.STATIC_DRAW)

	e.shader.vertCoord = gl.GetAttribLocation(e.shader.program, "vertCoord")
	e.shader.vertTexCoord = gl.GetAttribLocation(e.shader.program, "vertTexCoord")

	e.shader.projection = gl.GetUniformLocation(e.shader.program, "projection")
	e.shader.view = gl.GetUniformLocation(e.shader.program, "view")
	e.shader.model = gl.GetUniformLocation(e.shader.program, "model")

	e.shape.texture, err = LoadTexture("gopher.png")
	if err != nil {
		panic(fmt.Sprintln("LoadTexture failed:", err))
	}

	e.started = time.Now()
}
Exemplo n.º 3
0
func (p *PackageDeprecated) String() string {
	return fmt.Sprintln("   root:", p.root) +
		fmt.Sprintln("   name:", p.name) +
		fmt.Sprintln("version:", p.version) +
		fmt.Sprintln(" source:", p.Source) +
		fmt.Sprintln(" tmpdir:", p.tmpdir)
}
Exemplo n.º 4
0
func (this DepthMap) String() string {
	s := fmt.Sprintln("Depths", len(this))
	for _, dData := range this {
		s += fmt.Sprintln("Depth:", dData.depth, "Items:", len(dData.array))
	}
	return s
}
Exemplo n.º 5
0
func runPrune(dockerCli *command.DockerCli, opts pruneOptions) (spaceReclaimed uint64, output string, err error) {
	pruneFilters := opts.filter.Value()
	pruneFilters.Add("dangling", fmt.Sprintf("%v", !opts.all))

	warning := danglingWarning
	if opts.all {
		warning = allImageWarning
	}
	if !opts.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) {
		return
	}

	report, err := dockerCli.Client().ImagesPrune(context.Background(), pruneFilters)
	if err != nil {
		return
	}

	if len(report.ImagesDeleted) > 0 {
		output = "Deleted Images:\n"
		for _, st := range report.ImagesDeleted {
			if st.Untagged != "" {
				output += fmt.Sprintln("untagged:", st.Untagged)
			} else {
				output += fmt.Sprintln("deleted:", st.Deleted)
			}
		}
		spaceReclaimed = report.SpaceReclaimed
	}

	return
}
Exemplo n.º 6
0
func UpdatePortContext(ovs *libovsdb.OvsdbClient, portName string, key string, context string) error {
	config := make(map[string]string)
	config[CONTEXT_KEY] = key
	config[CONTEXT_VALUE] = context
	other_config, _ := libovsdb.NewOvsMap(config)

	mutation := libovsdb.NewMutation("other_config", "insert", other_config)
	condition := libovsdb.NewCondition("name", "==", portName)

	// simple mutate operation
	mutateOp := libovsdb.Operation{
		Op:        "mutate",
		Table:     "Interface",
		Mutations: []interface{}{mutation},
		Where:     []interface{}{condition},
	}

	operations := []libovsdb.Operation{mutateOp}
	reply, _ := ovs.Transact("Open_vSwitch", operations...)
	if len(reply) < len(operations) {
		return errors.New("Number of Replies should be atleast equal to number of Operations")
	}
	for i, o := range reply {
		if o.Error != "" && i < len(operations) {
			return errors.New(fmt.Sprintln("Transaction Failed due to an error :", o.Error, " details:", o.Details, " in ", operations[i]))
		} else if o.Error != "" {
			return errors.New(fmt.Sprintln("Transaction Failed due to an error :", o.Error))
		}
	}
	return nil
}
Exemplo n.º 7
0
func LoadRawTx(buf []byte) (s string) {
	txd, er := hex.DecodeString(string(buf))
	if er != nil {
		txd = buf
	}

	// At this place we should have raw transaction in txd
	tx, le := btc.NewTx(txd)
	if tx == nil || le != len(txd) {
		s += fmt.Sprintln("Could not decode transaction file or it has some extra data")
		return
	}
	tx.Hash = btc.NewSha2Hash(txd)

	var missinginp bool
	var totinp, totout uint64
	s, missinginp, totinp, totout, er = DecodeTx(tx)
	if er != nil {
		return
	}

	network.TxMutex.Lock()
	if missinginp {
		network.TransactionsToSend[tx.Hash.Hash] = &network.OneTxToSend{Tx: tx, Data: txd, Own: 2, Firstseen: time.Now(),
			Volume: totout}
	} else {
		network.TransactionsToSend[tx.Hash.Hash] = &network.OneTxToSend{Tx: tx, Data: txd, Own: 1, Firstseen: time.Now(),
			Volume: totinp, Fee: totinp - totout}
	}
	network.TxMutex.Unlock()
	s += fmt.Sprintln("Transaction added to the memory pool. Please double check its details above.")
	s += fmt.Sprintln("If it does what you intended, you can send it the network.\nUse TxID:", tx.Hash.String())
	return
}
Exemplo n.º 8
0
func (p *Pattern) String() string {
	if p == nil {
		return ""
	}

	var buffer bytes.Buffer
	buffer.WriteString(fmt.Sprintln("Saved with HW Version:", p.version))
	buffer.WriteString(fmt.Sprintln("Tempo:", p.tempo))

	for _, j := range p.track {
		buffer.WriteString(fmt.Sprint("(", strconv.Itoa(int(j.id)), ") ", j.name, "\t"))
		step := 0
		for i := 0; i < 16; i++ {
			if math.Mod(float64(step), 4) == 0 {
				//buffer.WriteByte(0x7C)
				buffer.WriteString("|")
			}
			if bytes.Compare(j.step[i:i+1], []byte{0x00}) == 0 {
				buffer.WriteString("-")
			} else if bytes.Compare(j.step[i:i+1], []byte{0x01}) == 0 {
				buffer.WriteString("x")
			} else {
				// incase if the byte is not 0x00 0x01
				buffer.WriteString(" ")
			}
			step = step + 1
			if i == 15 {
				buffer.WriteString("|")
				//buffer.WriteByte(0x7C)
			}
		}
		buffer.WriteString("\n")
	}
	return buffer.String()
}
Exemplo n.º 9
0
Arquivo: glm.go Projeto: Niriel/daggor
func MakeTaitBryan(h, p, r int) TaitBryan {
	if h < 0 || h > 3 {
		panic(fmt.Sprintln("Heading out of bound: %i not in [0, 1, 2].", h))
	}
	if p < 0 || p > 3 {
		panic(fmt.Sprintln("Pitch out of bound: %i not in [0, 1, 2].", p))
	}
	if r < 0 || r > 3 {
		panic(fmt.Sprintln("Roll out of bound: %i not in [0, 1, 2].", r))
	}
	if h == p {
		panic("Header and pitch must be different.")
	}
	if h == r {
		panic("Header and roll must be different.")
	}
	if p == r {
		panic("Pitch and roll must be different.")
	}
	var tb TaitBryan
	tb.h = h
	tb.p = p
	tb.r = r
	return tb
}
// Query the SHOW variables from the query map
// TODO: make this more functional
func queryShowVariables(ch chan<- prometheus.Metric, db *sql.DB, variableMap map[string]MetricMapNamespace) []error {
	log.Debugln("Querying SHOW variables")
	nonFatalErrors := []error{}

	for _, mapping := range variableMap {
		for columnName, columnMapping := range mapping.columnMappings {
			// Check for a discard request on this value
			if columnMapping.discard {
				continue
			}

			// Use SHOW to get the value
			row := db.QueryRow(fmt.Sprintf("SHOW %s;", columnName))

			var val interface{}
			err := row.Scan(&val)
			if err != nil {
				nonFatalErrors = append(nonFatalErrors, errors.New(fmt.Sprintln("Error scanning runtime variable:", columnName, err)))
				continue
			}

			fval, ok := columnMapping.conversion(val)
			if !ok {
				nonFatalErrors = append(nonFatalErrors, errors.New(fmt.Sprintln("Unexpected error parsing column: ", namespace, columnName, val)))
				continue
			}

			ch <- prometheus.MustNewConstMetric(columnMapping.desc, columnMapping.vtype, fval)
		}
	}

	return nonFatalErrors
}
Exemplo n.º 11
0
//compresses ram banks and stores as base64 strings.
//hashes are taken each bank
//information is stored on disk in JSON format
func (s *SaveFile) Save(data [][]byte) error {
	s.NoOfBanks = len(data)
	s.Banks = make([]string, s.NoOfBanks)
	s.BankHashes = make([]uint32, s.NoOfBanks)
	s.LastSaved = fmt.Sprint(time.Now().Format(time.UnixDate))

	log.Println("Saving RAM to", s.Path)
	for i, bank := range data {
		//take crc32 hash of bank
		s.BankHashes[i] = crc32.ChecksumIEEE(bank)

		//compress
		bankStr, err := s.DeflateBank(bank)
		if err != nil {
			return errors.New(fmt.Sprintln("Error attempting to compress bank %d (%v)", i, err))
		}

		log.Printf("--> Storing bank %d (Compression ratio: %.1f%%)", i, 100.00-((float32(len(bankStr))/float32(len(bank)))*100))
		s.Banks[i] = bankStr
	}

	//serialize to JSON
	js, err := json.Marshal(&s)
	if err != nil {
		return errors.New(fmt.Sprintln("Error attempting to parse into JSON", err))
	}

	log.Println("Save file", s.Path, "size is", len(js), "bytes")

	//write to disk
	return ioutil.WriteFile(s.Path, js, 0755)
}
Exemplo n.º 12
0
func setCodeAndBody(w Response, code int, body interface{}) {
	var contentType string
	var data []byte
	var err error

	if jsonMap, ok := body.(map[string]interface{}); ok {
		data, err = json.Marshal(jsonMap)
		if err != nil {
			w.ServerError("json marshal: ", err)
			http.Error(w, fmt.Sprintln("Server Error: unexpected Ok body type"), 500)
			return
		}
		contentType = "application/json; charset=utf-8"
	} else if str, ok := body.(string); ok {
		contentType = "text/plain; charset=utf-8"
		data = []byte(str)
	} else {
		log.Printf("ERROR: unexpected Ok body type: %T\n", body)
		http.Error(w, fmt.Sprintln("Server Error: unexpected Ok body type"), 500)
		return
	}

	w.Header().Set("Content-Type", contentType)
	w.WriteHeader(code)
	w.Write(data)
	// log.Println("setCodeAndBody:", code, contentType, body)
	log.Println("    HTTP", code, ",", contentType, ",", len(data), "bytes")
}
Exemplo n.º 13
0
func graphiteWorker(lCh chan string, gCh chan string, wg *sync.WaitGroup, host string, port uint16) {
	defer wg.Done()

	var (
		err error
	)

	graphite := Graphite{Host: host, Port: port}
	err = graphite.connect()
	for err != nil {
		lCh <- fmt.Sprintf("Connect Failure: Graphite has failed to connect, attempting reconnect in %d seconds.", 15)
		time.Sleep(time.Second * 15)
		err = graphite.connect()
	}

	for m := range gCh {

		lCh <- "Sending Metric: " + m

		err = graphite.sendMetric(m)
		for err != nil {
			lCh <- fmt.Sprintln("SendMetric Failure: Metric has failed to send, attempting to reconnect.")
			err = graphite.connect()
			if err != nil {
				lCh <- fmt.Sprintln("Connect Failure: Graphite has failed to connect.")
				lCh <- fmt.Sprintf("Connect Failure: Re-queuing metric and attempting reconnect in %d seconds.", 15)
				gCh <- m
				time.Sleep(time.Second * 15)
			}
		}

	}
}
Exemplo n.º 14
0
func handleConnection(conn net.Conn, msg_ch chan string, conn_ch chan net.Conn, rm_conn_ch chan net.Conn) {

	conn.Write([]byte("What is your name?"))
	data := make([]byte, 512)
	_, err := conn.Read(data)
	if err != nil {
		fmt.Println(err)
		conn.Close()
		fmt.Println("user disconnected")
		return
	}

	name := string(data)
	msg_ch <- fmt.Sprintln(name, "joined the server")

	conn_ch <- conn

	for {
		data := make([]byte, 512)
		_, err := conn.Read(data)
		if err != nil {
			fmt.Println(err)
			conn.Close()
			fmt.Println(name, "disconnected")
			rm_conn_ch <- conn
			msg_ch <- string(name + " disconnected")
			return
		}
		fmt.Println(name, ": ", string(data))
		msg_ch <- fmt.Sprintln(name, ":", string(data))
	}
}
Exemplo n.º 15
0
func (s *syslogBackend) Log(e *Event) {
	if e.IsUp() {
		s.writer.Info(fmt.Sprintln(e.Check.Key, btos(e.IsUp()), e.Duration))
	} else {
		s.writer.Err(fmt.Sprintln(e.Check.Key, btos(e.IsUp()), e.Duration))
	}
}
Exemplo n.º 16
0
func main() {
	var i, k int
	var r string
outer:
	for k = 0; k < 2; k++ {
		r += fmt.Sprintln("outer loop top k", k)
		if k != 0 {
			panic("k not zero")
		} // inner loop breaks this one every time
		for i = 0; i < 2; i++ {
			if i != 0 {
				panic("i not zero")
			} // loop breaks every time
			r += fmt.Sprintln("inner loop top i", i)
			if true {
				r += "do break\n"
				break outer
			}
		}
	}
	r += "broke\n"
	expect := `outer loop top k 0
inner loop top i 0
do break
broke
`
	if r != expect {
		panic(r)
	}
}
Exemplo n.º 17
0
//	Parse string messages received from StdIn
func Parse(str string) error {
	strs := strings.Split(str, " ")
	if len(strs) <= 1 {
		e := fmt.Sprintln("Parsing error in mainUI, not enough elements in given string",
			strs)
		return errors.New(e)
	}
	//	Get is a request for information from mainUI
	if strs[0] == "Get" {
		switch strs[1] {
		case "pluginRpcAddress":
		default:
			fmt.Println(skel.LogPrefix(), "Unrecognised Get request", strs)
		}
		//	Push is for information sent to mainUI that do not require an answer.
	} else if strs[0] == "Push" {
		switch strs[1] {
		case "quit":
			fmt.Println(skel.LogPrefix(), "Received Quit signal")
		case "log":
			fmt.Println(skel.LogPrefix(), strings.Join(strs[2:], " "))
		}
	} else {
		e := fmt.Sprintln("Parsing error in mainUI, no match for string sequence:",
			strs)
		return errors.New(e)
	}
	return nil
}
Exemplo n.º 18
0
/*
	Tango supports 5 form funcs

	func()
	func(*Context)
	func(http.ResponseWriter, *http.Request)
	func(http.ResponseWriter)
	func(*http.Request)

	it can has or has not return value
*/
func (router *router) addFunc(methods []string, url string, c interface{}) {
	vc := reflect.ValueOf(c)
	t := vc.Type()
	var rt RouteType

	if t.NumIn() == 0 {
		rt = FuncRoute
	} else if t.NumIn() == 1 {
		if t.In(0) == reflect.TypeOf(new(Context)) {
			rt = FuncCtxRoute
		} else if t.In(0) == reflect.TypeOf(new(http.Request)) {
			rt = FuncReqRoute
		} else if t.In(0).Kind() == reflect.Interface && t.In(0).Name() == "ResponseWriter" &&
			t.In(0).PkgPath() == "net/http" {
			rt = FuncResponseRoute
		} else {
			panic(fmt.Sprintln("no support function type", methods, url, c))
		}
	} else if t.NumIn() == 2 &&
		(t.In(0).Kind() == reflect.Interface && t.In(0).Name() == "ResponseWriter" &&
			t.In(0).PkgPath() == "net/http") &&
		t.In(1) == reflect.TypeOf(new(http.Request)) {
		rt = FuncHttpRoute
	} else {
		panic(fmt.Sprintln("no support function type", methods, url, c))
	}

	var r = NewRoute(c, t, vc, rt)
	url = removeStick(url)
	for _, m := range methods {
		router.addRoute(m, url, r)
	}
}
Exemplo n.º 19
0
func main() {
	ln, err := net.Listen("tcp", ":9000")
	if err != nil {
		log.Fatalln("listen messed up", err.Error())
		panic(err)
	}
	defer ln.Close()

	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Fatalln("conn messed up", err.Error())
			panic(err)
		}

		for {
			var bs = make([]byte, 1024)
			n, err := conn.Read(bs)
			if err != nil {
				break
			}

			m, err := conn.Write(bs)
			if err != nil {
				break
			}
			io.WriteString(conn, fmt.Sprintln("Bytes read: ", n))
			io.WriteString(conn, fmt.Sprintln("Bytes written: ", m))

		}
		conn.Close()
	}
}
Exemplo n.º 20
0
func help() string {
	msg := ""
	msg += fmt.Sprintln("0.输入\"?\"或者\"help\" 显示帮助")
	msg += fmt.Sprintln("1.输入股票代码(如\"600360\")显示当前价")
	msg += fmt.Sprintln("2.输入gold(如\"gold\")显示当前金价")
	return msg
}
Exemplo n.º 21
0
// Run method to run the task and Task implements Runnable interface
func (task *Task) Run(logfile *os.File) error {

	// Starting execution
	logfile.WriteString(fmt.Sprintf("%10v Executing %10v\n", time.Now(), task.Name))

	// Switch according to the command type
	switch task.ComType {

	// if a message, just put it in the logfile
	case "message":
		logfile.WriteString(fmt.Sprintln("Output for task", task.Name, ":\n", task.Command))

	// if an executable run it
	case "exec":

		// Get the output of the execution
		out, err := exec.Command(task.Command).Output()

		// Check for errors in the execution
		if err != nil {
			// Write errors to logfile
			logfile.WriteString(fmt.Sprintln("Error for task", task.Name, ":\n", err))
			return err
		}

		// Write the output to the logfile
		logfile.WriteString(fmt.Sprintln("Output for task", task.Name, ":\n", string(out)))
	}
	return nil
}
Exemplo n.º 22
0
func (o Object) String() string {
	switch o.Type {
	case BlobT:
		if o.blob == nil {
			return "broken blob"
		}
		return fmt.Sprintf("blob<%d> %q", o.Size, string(*o.blob))
	case TreeT:
		if o.tree == nil {
			return "broken tree"
		}
		s := fmt.Sprintf("tree<%d>\n", o.Size)
		for _, t := range o.tree {
			s += fmt.Sprintf("%q\t%q\t%s\n", t.Mode, t.Name, t.SHA1Sum)
		}
		return s
	case CommitT:
		if o.commit == nil {
			return "broken commit"
		}
		s := fmt.Sprintf("commit<%d>\n", o.Size)
		s += fmt.Sprintln("Tree:", o.commit.Tree)
		s += fmt.Sprintln("Author:", o.commit.Author)
		s += fmt.Sprintln("Committer:", o.commit.Committer)
		s += o.commit.Message
		return s
	default:
		return "broken object"
	}
}
Exemplo n.º 23
0
func CheckServiceTasks(awsConn *ecs.ECS, clusterName string,
	serviceName string, verboseFlag bool, serviceTaskDefinition string) ([]string, int) {
	taskWarnings := make([]string, 0)

	serviceTaskRevision := getRevisionFromTaskDefinition(serviceTaskDefinition)
	tasks := getServiceTasks(awsConn, clusterName, serviceName)

	var taskRunning = 0
	for _, task := range tasks {
		if verboseFlag {
			taskWarnings = append(taskWarnings, fmt.Sprintln("  - Task", *task.TaskArn))
			taskWarnings = append(taskWarnings, fmt.Sprintln("    Task Def:", *task.TaskDefinitionArn))
			taskWarnings = append(taskWarnings, fmt.Sprintln("    Desired status", *task.DesiredStatus, "- Last status", *task.LastStatus))
		}
		if *task.LastStatus == "RUNNING" {
			taskRunning += 1
		}
		taskRevision := getRevisionFromTaskDefinition(*task.TaskDefinitionArn)
		if serviceTaskRevision != taskRevision {
			taskWarnings = append(taskWarnings, fmt.Sprintln("WARNING: task uses", taskRevision, "but service definition is", serviceTaskRevision))
		}
	}
	if taskRunning == 0 {
		taskWarnings = append(taskWarnings, fmt.Sprintln("WARNING: No tasks in RUNNING state for the service"))
	}
	return taskWarnings, taskRunning
}
Exemplo n.º 24
0
// String returns a string reprentation of the histogram,
// which is useful for printing to a terminal.
func (h *NumericHistogram) String() (str string) {
	str += fmt.Sprintln("Total:", h.total)

	maxLen := 0
	for i := range h.bins {
		l := len(fmt.Sprintf("%.2f", h.bins[i].value))
		if l > maxLen {
			maxLen = l
		}
	}

	for i := range h.bins {
		var bar string
		for j := 0; j < int(float64(h.bins[i].count)/float64(h.total)*200); j++ {
			bar += "."
		}
		v := fmt.Sprintf("%.2f", h.bins[i].value)
		for len(v) <= maxLen {
			v += " "
		}
		str += fmt.Sprintln(v, bar)
	}

	return
}
Exemplo n.º 25
0
func main() {
	cgreader.RunStaticProgram(
		"../../input/mime_types_5.txt",
		"../../output/mime_types_5.txt",
		true,
		func(input <-chan string, output chan string) {
			var n, m int
			fmt.Sscanf(<-input, "%d", &n)
			fmt.Sscanf(<-input, "%d", &m)

			types := make(map[string]string)
			for i := 0; i < n; i++ {
				var key, value string
				fmt.Sscanf(<-input, "%s %s", &key, &value)
				types[strings.ToLower(key)] = value
			}

			for i := 0; i < m; i++ {
				var path string
				fmt.Sscanf(<-input, "%s", &path)
				path = strings.ToLower(path)

				if strings.Contains(path, ".") {
					sp := strings.Split(path, ".")
					if value, ok := types[sp[len(sp)-1]]; ok {
						output <- fmt.Sprintf("%s\n", value)
					} else {
						output <- fmt.Sprintln("UNKNOWN")
					}
				} else {
					output <- fmt.Sprintln("UNKNOWN")
				}
			}
		})
}
Exemplo n.º 26
0
func (this *Game) String() string {
	s := fmt.Sprintln(this.Holes, this.Board)
	if this.Actor != -1 {
		s += fmt.Sprintln(this.Pot(), this.Bets, this.CallAmt(), this.RaiseAmt())
	}
	return s
}
Exemplo n.º 27
0
func (p *Pattern) String() string {
	var output string

	// Output Version & Tempo
	output += fmt.Sprintln("Saved with HW Version:", p.Version)
	output += fmt.Sprintln("Tempo:", p.Tempo)

	// Loop over each track, printing id, name and beats for each one
	for _, track := range p.Tracks {
		output += fmt.Sprintf("(%d) %s\t", track.ID, track.Name)

		// Print the beats by first printing a line each 4 beats,
		// then printing 'x' for a beat, '-' for a non-beat
		for k, v := range track.Beats {
			if k%4 == 0 {
				output += fmt.Sprint("|")
			}
			if v == 1 {
				output += fmt.Sprint("x")
			} else {
				output += fmt.Sprint("-")
			}
		}

		// Add a closing '|'
		output += fmt.Sprintln("|")
	}
	return output
}
Exemplo n.º 28
0
func (c *Cartridge) String() string {
	startingString := "Gameboy"
	if c.IsColourGB {
		startingString += " Color"
	}

	var destinationRegion string
	if c.IsJapanese {
		destinationRegion = "Japanese"
	} else {
		destinationRegion = "Non-Japanese"
	}

	var header []string = []string{
		fmt.Sprintf(utils.PadRight("Title:", 19, " ")+"%s", c.Title),
		fmt.Sprintf(utils.PadRight("Type:", 19, " ")+"%s %s", c.Type.Description, utils.ByteToString(c.Type.ID)),
		fmt.Sprintf(utils.PadRight("Destination code:", 19, " ")+"%s", destinationRegion),
		fmt.Sprintf(utils.PadRight("File:", 19, " ")+"%s", c.Filename),
	}

	return fmt.Sprintln("\n"+startingString, "Cartridge") +
		fmt.Sprintln(strings.Repeat("-", 100)) +
		fmt.Sprintln(strings.Join(header, "\n")) +
		fmt.Sprintln(c.MBC) +
		fmt.Sprintln(strings.Repeat("-", 100))
}
Exemplo n.º 29
0
func (n *Namecard) String() (ret string) {
	ret += fmt.Sprintln("\n==============================")
	ret += fmt.Sprintln("\tName:", n.Name)
	ret += fmt.Sprintln("\tAge:", n.Age)
	ret += fmt.Sprintln("==============================")
	return ret
}
Exemplo n.º 30
0
//setupPurgeReceiver set up the tcp socket where ban messages come
//when a purge pattern is received it dispatches it to a Pub object
func setupPurgeReceiver(incomingAddress *string, publisher *Publisher) {
	receiver, err := net.Listen("tcp", *incomingAddress)
	utils.CheckError(err, logger)

	go func() {
		ping := []byte("ping")
		for {
			time.Sleep(5 * time.Second)
			publisher.Pub(ping)
		}
	}()
	for {
		conn, err := receiver.Accept()
		utils.CheckError(err, logger)
		go func(c net.Conn) {
			defer conn.Close()
			b, err := ioutil.ReadAll(conn)
			if err != nil {
				logger.Info(fmt.Sprintln("Client connection error:", err))
			} else {
				clean_purge := bytes.TrimSpace(b)
				logger.Info(fmt.Sprintln("<-", utils.ReverseName(conn), string(clean_purge)))
				publisher.Pub(clean_purge)
				conn.Write([]byte("OK\n"))
			}
		}(conn)
	}
	return
}