コード例 #1
0
func TestCustomPrefix(t *testing.T) {
	Convey("Given the App running with PREFIX", t, func() {
		uc := make(chan string, 0)
		bc := make(chan string, 0)
		f := Flag
		f.Prefix = "BETA"
		ctx, _ := context.WithCancel(context.Background())
		ctx = context.WithValue(ctx, "Flag", f)
		app := NewApp(ctx, GetMockPerformJsonPost(uc, bc))
		v1httpapi := V1HttpApi{
			App: app,
		}
		v1httpapi.registerRoutes(app.Router)

		Convey("When posting a message", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			post_body := bytes.NewReader([]byte(""))
			http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body)

			So(<-uc, ShouldEqual, "http://"+f.ApiEndPoint+"/v1/log/bulk/")
			body := <-bc
			So(body, ShouldContainSubstring, "\"__prefix\":\"BETA\"")
			So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"")
			So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"")
			So(body, ShouldContainSubstring, "\"__namespace\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"")
		})

	})

	Convey("Given the App running WITHOUT prefix", t, func() {
		uc := make(chan string, 0)
		bc := make(chan string, 0)
		f := Flag
		ctx, _ := context.WithCancel(context.Background())
		ctx = context.WithValue(ctx, "Flag", f)
		app := NewApp(ctx, GetMockPerformJsonPost(uc, bc))
		v1httpapi := V1HttpApi{
			App: app,
		}
		v1httpapi.registerRoutes(app.Router)

		Convey("When posting a message", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			post_body := bytes.NewReader([]byte(""))
			http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body)

			So(<-uc, ShouldEqual, "http://"+f.ApiEndPoint+"/v1/log/bulk/")
			body := <-bc
			So(body, ShouldNotContainSubstring, "\"__prefix\"")
			So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"")
			So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"")
			So(body, ShouldContainSubstring, "\"__namespace\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"")
		})

	})
}
コード例 #2
0
ファイル: main.go プロジェクト: zoglee/netty
func HandleConnection(ctx context.Context, tcpconn *net.TCPConn) {
	ctx, cancel := context.WithCancel(ctx)
	defer func() {
		tcpconn.Close()
		if err := recover(); err != nil {
			glog.Errorf("tcpconn panic: %s", err)
		}
		cancel()
	}()

	sysfd, err := SysfdByTcpConn(tcpconn)
	if err != nil {
		glog.Errorf("SysfdByTcpConn err: %s, addr: %s, fd=%d",
			err, tcpconn.RemoteAddr().String(), sysfd)
		return
	}

	glog.Infof("Start handle conn, addr: %s, fd=%d", tcpconn.RemoteAddr().String(), sysfd)

	errc := make(chan error)
	inreqc := make(chan *Request, 10) // TODO(zog): is 10 a good number?
	reqc := Recv(ctx, errc, sysfd, tcpconn)
	rspc := Send(ctx, errc, sysfd, tcpconn)
	Work(ctx, errc, sysfd, reqc, inreqc, rspc)
	Update(ctx, errc, sysfd, rspc)

	exportInnerReqChan(sysfd, tcpconn, inreqc)

	if err := <-errc; err != nil {
		glog.Errorf("HandleConnection err: %v, addr: %s", err, tcpconn.RemoteAddr().String())
	}

	glog.Infof("Stop handle conn, addr: %s, fd=%d", tcpconn.RemoteAddr().String(), sysfd)
}
コード例 #3
0
ファイル: context.go プロジェクト: rht/go-datastore
// WithProcessClosed returns a context.Context that is cancelled
// after Process p is Closed. It is the equivalent of:
//
//   func WithProcessClosed(ctx context.Context, p goprocess.Process) context.Context {
//     ctx, cancel := context.WithCancel(ctx)
//     go func() {
//       <-p.Closed()
//       cancel()
//     }()
//     return ctx
//   }
//
func WithProcessClosed(ctx context.Context, p goprocess.Process) context.Context {
	ctx, cancel := context.WithCancel(ctx)
	go func() {
		<-p.Closed()
		cancel()
	}()
	return ctx
}
コード例 #4
0
ファイル: tomb.go プロジェクト: bryanxu/go-zh.blog
// NewContext returns a Context that is canceled either when parent is canceled
// or when t is Killed.
func NewContext(parent context.Context, t *tomb.Tomb) context.Context {
	ctx, cancel := context.WithCancel(parent)
	go func() {
		select {
		case <-t.Dying():
			cancel()
		case <-ctx.Done():
		}
	}()
	return ctx
}
コード例 #5
0
ファイル: server.go プロジェクト: bryanxu/go-zh.blog
// handleSearch handles URLs like /search?q=golang&timeout=1s by forwarding the
// query to google.Search. If the query param includes timeout, the search is
// canceled after that duration elapses.
func handleSearch(w http.ResponseWriter, req *http.Request) {
	// ctx is the Context for this handler. Calling cancel closes the
	// ctx.Done channel, which is the cancellation signal for requests
	// started by this handler.
	var (
		ctx    context.Context
		cancel context.CancelFunc
	)
	timeout, err := time.ParseDuration(req.FormValue("timeout"))
	if err == nil {
		// The request has a timeout, so create a context that is
		// canceled automatically when the timeout expires.
		ctx, cancel = context.WithTimeout(context.Background(), timeout)
	} else {
		ctx, cancel = context.WithCancel(context.Background())
	}
	defer cancel() // Cancel ctx as soon as handleSearch returns.

	// Check the search query.
	query := req.FormValue("q")
	if query == "" {
		http.Error(w, "no query", http.StatusBadRequest)
		return
	}

	// Store the user IP in ctx for use by code in other packages.
	userIP, err := userip.FromRequest(req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	ctx = userip.NewContext(ctx, userIP)

	// Run the Google search and print the results.
	start := time.Now()
	results, err := google.Search(ctx, query)
	elapsed := time.Since(start)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if err := resultsTemplate.Execute(w, struct {
		Results          google.Results
		Timeout, Elapsed time.Duration
	}{
		Results: results,
		Timeout: timeout,
		Elapsed: elapsed,
	}); err != nil {
		log.Print(err)
		return
	}
}
コード例 #6
0
func TestPostMany(t *testing.T) {
	Convey("Given the App running", t, func() {
		uc := make(chan string, 0)
		bc := make(chan string, 0)
		f := Flag
		f.BufferSize = 100
		f.BufferTimeout = "100ms"
		ctx, _ := context.WithCancel(context.Background())
		ctx = context.WithValue(ctx, "Flag", f)
		app := NewApp(ctx, GetMockPerformJsonPost(uc, bc))
		v1httpapi := V1HttpApi{
			App: app,
		}
		v1httpapi.registerRoutes(app.Router)

		Convey("When posting BufferSize + 10 messages", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			for i := 1; i <= f.BufferSize+10; i++ {
				post_body := bytes.NewReader([]byte("{\"i\":\"" + strconv.Itoa(i) + "\"}"))
				http.Post(ts.URL+"/log/many/at/once/", "application/json", post_body)
			}

			So(<-uc, ShouldEqual, "http://"+f.ApiEndPoint+"/v1/log/bulk/")
			body := <-bc
			So(body, ShouldContainSubstring, "\"__level\":\"many\"")
			So(body, ShouldContainSubstring, "\"__category\":\"at\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"once\"")
			for i := 1; i <= f.BufferSize; i++ {
				So(body, ShouldContainSubstring, "\"i\":\""+strconv.Itoa(i)+"\"")
			}
			So(<-uc, ShouldEqual, "http://"+f.ApiEndPoint+"/v1/log/bulk/")
			body = <-bc
			for i := f.BufferSize + 1; i <= f.BufferSize+10; i++ {
				So(body, ShouldContainSubstring, "\"i\":\""+strconv.Itoa(i)+"\"")
			}

			body = "EMPTY"
			var uc_value string = "EMPTY"
			select {
			case uc_value = <-uc:
			case <-time.After(time.Second):
			}
			select {
			case body = <-bc:
			case <-time.After(time.Second):
			}
			So(uc_value, ShouldEqual, "EMPTY")
			So(body, ShouldEqual, "EMPTY")
		})

	})
}
コード例 #7
0
func TestHandleMultipleConnections(t *testing.T) {
	// to be sent to each connecting clients
	response := []byte("a response\n")

	handle := func(ctx context.Context, conn net.Conn) error {
		conn.Write(response)
		return nil
	}

	// done will close when tcpserver returns
	done := make(chan struct{})

	// start tcp server
	port := ":4444"
	ctx, cancel := context.WithCancel(context.Background())
	go func() {
		err := Listen(ctx, port, handle)
		if err != nil {
			t.Error(err)
		}
		close(done)
	}()

	// make 5 client requests
	for i := 0; i < 5; i++ {
		conn, err := net.Dial("tcp", "localhost"+port)
		if err != nil {
			t.Error(err)
		}

		resp, err := bufio.NewReader(conn).ReadString('\n')
		if err != nil {
			t.Error(err)
		}

		if resp != string(response) {
			t.Error("got %s but expected %s", resp, string(response))
		}
	}

	cancel()

	// wait for tcpserver to cleanup
	select {
	case <-done:
	case <-time.After(3 * time.Second):
		t.Error("tcpserver did not cleanup in time")
	}
}
コード例 #8
0
ファイル: server.go プロジェクト: htee/htee
func (s *server) handleRequest(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	ctx = newContext(ctx, r)

	switch r.Method {
	case "GET":
		s.playbackStream(ctx, w, r)
	case "POST":
		s.recordStream(ctx, w, r)
	case "DELETE":
		s.deleteStream(ctx, w, r)
	}
}
コード例 #9
0
ファイル: aggregator.go プロジェクト: mikechack/wsrouter
func main() {

	var server string

	var (
		ctx    context.Context
		cancel context.CancelFunc
	)

	ctx, cancel = context.WithCancel(context.Background())

	runtime.GOMAXPROCS(1)

	server = os.Args[1]
	id := os.Args[2]

	LogConditional(printLog, fmt.Printf, "Client Id %s\n", id)
	//fmt.Printf("Client Id %s\n", id)

	var headers http.Header = make(http.Header)
	headers.Add("X-Client-ID", id)

	var srvurl = "ws://173.39.210.210:8080/echo/"

	origin = fmt.Sprintf("http://%s/", server)
	srvurl = fmt.Sprintf("ws://%s:8080/echo/?id=%s", server, id)

	u, err := url.Parse(srvurl)
	o, err := url.Parse(origin)
	ws, err := websocket.DialConfig(&websocket.Config{Location: u, Header: headers, Origin: o, Version: 13})

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

	c := make(chan []byte)

	go collectdTcp(cancel, c)
	go collectSyslog(c)
	go writer(ws, id, c)
	//go reader(ws, id)

	select {
	case <-ctx.Done():
	}

}
コード例 #10
0
ファイル: ipfs.go プロジェクト: vijayee/Account
// create a new Service
func NewService(name string, location string) (Service, error) {
	// Basic ipfsnode setup
	repo, err := fsrepo.Open(location)
	if err != nil {
		return Service{}, err
	}
	nodeBuilder := core.NewNodeBuilder().Online()
	nodeBuilder.SetRepo(repo)

	ctx, cancel := context.WithCancel(context.Background())

	node, err := nodeBuilder.Build(ctx)
	if err != nil {
		return Service{}, err
	}
	return Service{name, node, cancel, ctx, nil, make(chan bool), false}, nil
}
コード例 #11
0
ファイル: pubsub.go プロジェクト: john-cai/tools
func main() {
	flag.Parse()

	ctx, done := context.WithCancel(context.Background())

	go func() {
		publish(redial(ctx, *url), read(os.Stdin))
		done()
	}()

	go func() {
		subscribe(redial(ctx, *url), write(os.Stdout))
		done()
	}()

	<-ctx.Done()
}
コード例 #12
0
ファイル: wsclient.go プロジェクト: mikechack/wsrouter
func main() {

	var server string

	runtime.GOMAXPROCS(1)
	R = *new(responses)
	R.waiting = make(map[int64]response)
	rand.Seed(time.Now().UnixNano())
	var (
		ctx context.Context
	)

	ctx, _ = context.WithCancel(context.Background())

	server = os.Args[1]
	id := os.Args[2]
	printLog = (os.Args[3] == "1")
	fmt.Sscanf(os.Args[4], "%d", &loopCount)

	LogConditional(printLog, fmt.Printf, "Client Id %s\n", id)
	//fmt.Printf("Client Id %s\n", id)

	var headers http.Header = make(http.Header)
	headers.Add("X-Client-ID", id)

	var srvurl = "ws://173.39.210.210:8080/echo/"

	origin = fmt.Sprintf("http://%s/", server)
	srvurl = fmt.Sprintf("ws://%s:8080/echo/?id=%s", server, id)

	u, err := url.Parse(srvurl)
	o, err := url.Parse(origin)
	ws, err := websocket.DialConfig(&websocket.Config{Location: u, Header: headers, Origin: o, Version: 13})

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

	go writer(ws, id)
	go reader(ws, id)

	select {
	case <-ctx.Done():
	}

}
コード例 #13
0
func TestHeaderVariables(t *testing.T) {
	Convey("Given the App running", t, func() {
		uc := make(chan string, 0)
		bc := make(chan string, 0)
		ctx, _ := context.WithCancel(context.Background())
		f := Flag
		ctx = context.WithValue(ctx, "Flag", f)

		app := NewApp(ctx, GetMockPerformJsonPost(uc, bc))
		v1httpapi := V1HttpApi{
			App: app,
		}
		v1httpapi.registerRoutes(app.Router)

		Convey("When posting __namespace in the body", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()

			post_body := bytes.NewReader([]byte(""))

			client := &http.Client{}
			req, err := http.NewRequest("POST", ts.URL+"/log/fakelevel/fakecategory/fakeslug/", post_body)
			So(err, ShouldBeNil)
			req.Header.Add("__namespace", "some_custom_namespace")
			req.Header.Add("__date", "some_custom_date")
			req.Header.Add("Content-type", "application/json")
			resp, err := client.Do(req)
			defer resp.Body.Close()

			<-uc
			body := <-bc
			So(body, ShouldContainSubstring, "\"__namespace\":\"some_custom_namespace\"")
			So(body, ShouldContainSubstring, "\"__date\":\"some_custom_date\"")
			So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"")
			So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"")
			So(body, ShouldContainSubstring, "\"__namespace\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"")
		})

	})
}
コード例 #14
0
ファイル: context.go プロジェクト: se77en/jobber
func NewJobberContext(parent *JobberContext) (*JobberContext, JobberCtl) {
	parent.mutex.RLock()
	defer parent.mutex.RUnlock()

	// make context
	newCtxName := fmt.Sprintf("%v.%v", parent.Name, parent.childAmt)
	newImpl, newImplCancel := context.WithCancel(parent.impl)
	var newCtx *JobberContext = &JobberContext{
		Name:         newCtxName,
		impl:         newImpl,
		finishedChan: make(chan struct{}),
		finished:     false,
		parent:       parent,
	}
	Logger.Printf("New context: %v\n", newCtxName)

	// make control struct
	var newCtl JobberCtl

	// make control funcs
	newCtl.Cancel = func() <-chan struct{} {
		newImplCancel()
		return newCtx.finishedChan
	}
	newCtl.Wait = func() {
		<-newCtx.finishedChan
	}

	// update parent
	parent.childAmt++
	if parent.finished {
		newCtx.finished = true
		close(newCtx.finishedChan)
	} else {
		parent.childWaitGroup.Add(1)
	}

	return newCtx, newCtl
}
コード例 #15
0
ファイル: server.go プロジェクト: mikechack/wsrouter
func receiver(ws *websocket.Conn) {
	var (
		ctx    context.Context
		cancel context.CancelFunc
	)

	ctx, cancel = context.WithCancel(context.Background())

	c := make(chan *registrar.T)
	defer ws.Close()
	//defer close(c)
	defer cancel()
	ws.Request().ParseForm()
	id := ws.Request().FormValue("id")
	go transmitter(id, ws, c, ctx, cancel)
	err := registrar.NewConnection(id, c)
	if err != nil {
		fmt.Printf("New Connection Failed - Duplicate CLient Id %s\n", id)
	} else {
		for {
			var data *registrar.T = new(registrar.T)
			err := websocket.JSON.Receive(ws, data)
			if err != nil {
				log.Printf("echo handler error %v\n", err)
				break
			}
			data.From = id
			if data.Msg == "bye" {
				break
			}
			err = registrar.RouteMessage(data)
			if err != nil {
				log.Printf("Routing Error %v - %s\n", err, data.To)
			}
		}
	}
	registrar.RemoveConnection(id)

}
コード例 #16
0
ファイル: client.go プロジェクト: jchown/abe
func main() {
	if len(os.Args) < 2 {
		fmt.Println("Please give a peer ID as an argument")
		return
	}

	target, err := peer.IDB58Decode(os.Args[1])
	if err != nil {
		panic(err)
	}

	// Basic ipfsnode setup
	r := fsrepo.At("~/.ipfs")
	if err := r.Open(); err != nil {
		panic(err)
	}

	nb := core.NewNodeBuilder().Online()
	nb.SetRepo(r)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	nd, err := nb.Build(ctx)
	if err != nil {
		panic(err)
	}

	fmt.Printf("I am peer %s dialing %s\n", nd.Identity, target)

	con, err := corenet.Dial(nd, target, "/app/whyrusleeping")
	if err != nil {
		fmt.Println(err)
		return
	}

	io.Copy(os.Stdout, con)
}
コード例 #17
0
ファイル: util.go プロジェクト: KSCTECHNOLOGIES/uberlog
func NewContextFromConfig(c ConfigStruct) context.Context {
	ctx, _ := context.WithCancel(context.Background())
	ctx = context.WithValue(ctx, "Config", c)
	return ctx
}
コード例 #18
0
func TestPostToLogApi(t *testing.T) {
	Convey("Given the App running", t, func() {
		uc := make(chan string, 0)
		bc := make(chan string, 0)
		ctx, _ := context.WithCancel(context.Background())
		ctx = context.WithValue(ctx, "Flag", Flag)
		app := NewApp(ctx, GetMockPerformJsonPost(uc, bc))

		v1httpapi := V1HttpApi{
			App: app,
		}
		v1httpapi.registerRoutes(app.Router)

		Convey("When posting empty body", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			post_body := bytes.NewReader([]byte(""))
			http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body)

			So(<-uc, ShouldEqual, "http://"+Flag.ApiEndPoint+"/v1/log/bulk/")
			body := <-bc
			So(body, ShouldContainSubstring, "\"__date\"")
			So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"")
			So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"")
			So(body, ShouldContainSubstring, "\"__namespace\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"")
		})

		Convey("When posting {} as the body", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			post_body := bytes.NewReader([]byte("{}"))
			http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body)

			So(<-uc, ShouldEqual, "http://"+Flag.ApiEndPoint+"/v1/log/bulk/")
			body := <-bc
			So(body, ShouldContainSubstring, "\"__date\"")
			So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"")
			So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"")
			So(body, ShouldContainSubstring, "\"__namespace\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"")
		})

		Convey("When posting __date in the body", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			post_body := bytes.NewReader([]byte("{\"__date\":\"123\"}"))
			http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body)

			So(<-uc, ShouldEqual, "http://"+Flag.ApiEndPoint+"/v1/log/bulk/")
			body := <-bc
			So(body, ShouldContainSubstring, "\"__date\":\"123\"")
			So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"")
			So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"")
			So(body, ShouldContainSubstring, "\"__namespace\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"")
		})

		Convey("When posting __namespace in the body", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			post_body := bytes.NewReader([]byte("{\"__namespace\":\"my_namespace\"}"))
			http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body)

			So(<-uc, ShouldEqual, "http://"+Flag.ApiEndPoint+"/v1/log/bulk/")
			body := <-bc
			So(body, ShouldContainSubstring, "\"__namespace\":\"my_namespace\"")
			So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"")
			So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"")
			So(body, ShouldContainSubstring, "\"__namespace\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"")
		})

		Convey("When posting empty __namespace in the body", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			post_body := bytes.NewReader([]byte("{\"__namespace\":\"\"}"))
			http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body)

			So(<-uc, ShouldEqual, "http://"+Flag.ApiEndPoint+"/v1/log/bulk/")
			body := <-bc
			//should use the hostname as the namespace
			So(body, ShouldNotContainSubstring, "\"__namespace\":\"\"")
			So(body, ShouldContainSubstring, "\"__namespace\"")
			So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"")
			So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"")
			So(body, ShouldContainSubstring, "\"__namespace\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"")
		})

		Convey("When posting custom keys in the body", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			post_body := bytes.NewReader([]byte("{\"name\":\"John Doe\",\"date\":\"123\"}"))
			http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body)

			So(<-uc, ShouldEqual, "http://"+Flag.ApiEndPoint+"/v1/log/bulk/")
			body := <-bc
			//should use the hostname as the namespace
			So(body, ShouldNotContainSubstring, "\"__date\":\"123\"")
			So(body, ShouldContainSubstring, "\"__date\"")
			So(body, ShouldContainSubstring, "\"date\":\"123\"")
			So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"")
			So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"")
			So(body, ShouldContainSubstring, "\"name\":\"John Doe\"")
			So(body, ShouldContainSubstring, "\"date\":\"123\"")
		})

		Convey("When posting custom keys in the body", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			post_body := bytes.NewReader([]byte("{\"name\":\"John Doe\",\"date\":\"123\"}"))
			http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body)

			So(<-uc, ShouldEqual, "http://"+Flag.ApiEndPoint+"/v1/log/bulk/")
			body := <-bc
			//should use the hostname as the namespace
			So(body, ShouldNotContainSubstring, "\"__date\":\"123\"")
			So(body, ShouldContainSubstring, "\"__date\"")
			So(body, ShouldContainSubstring, "\"__category\":\"fakecategory\"")
			So(body, ShouldContainSubstring, "\"__level\":\"fakelevel\"")
			So(body, ShouldContainSubstring, "\"__slug\":\"fakeslug\"")
			So(body, ShouldContainSubstring, "\"name\":\"John Doe\"")
			So(body, ShouldContainSubstring, "\"date\":\"123\"")
		})

		Convey("When posting invalid json as the body", func() {
			ts := httptest.NewServer(app.Router)
			defer ts.Close()
			post_body := bytes.NewReader([]byte("THIS IS AN INVALID JSON"))
			http.Post(ts.URL+"/log/fakelevel/fakecategory/fakeslug/", "application/json", post_body)

			var uc_value string = "EMPTY"
			select {
			case uc_value = <-uc:
			case <-time.After(time.Second):
			}
			var body string = "EMPTY"
			select {
			case body = <-bc:
			case <-time.After(time.Second):
			}
			So(uc_value, ShouldEqual, "EMPTY")
			So(body, ShouldEqual, "EMPTY")
		})
	})
}
コード例 #19
0
ファイル: main.go プロジェクト: rdterner/dhtHell
func main() {
	cmdfile := flag.String("f", "", "a file of commands to run")
	serv := flag.String("s", "", "address to run d3 viz server on")
	rpc := flag.Bool("r", false, "whether or not to turn on rpc")
	def := flag.Bool("default", false, "whether or not to load default config")
	ins := flag.Bool("inspect", false, "whether or not to inspect stack afterwards")
	quiet := flag.Bool("q", false, "supress obnoxious log messages")
	flag.Parse()
	logquiet = *quiet

	setuprpc = *rpc

	u.Debug = true
	runtime.GOMAXPROCS(10)

	if *serv != "" {
		go RunServer(*serv)
	}

	// Setup Configuration and inputs
	var scan *bufio.Scanner
	testconf := new(testConfig)
	if *cmdfile != "" {
		fiscan, err := ParseCommandFile(*cmdfile, testconf)
		if err != nil {
			fmt.Println(err)
			return
		}
		scan = fiscan
	} else {
		scan = bufio.NewScanner(os.Stdin)
		if *def { // Default configuration
			testconf.NumNodes = 15
			SetupNConfigs(testconf)
			for _, cfg := range configs[1:] {
				BootstrapTo(cfg, configs[0])
			}
		} else {
			ConfigPrompt(scan)
			if scan.Err() != nil {
				fmt.Printf("Scan error: %s\n", scan.Err())
			}
		}
	}

	ctx, cancel := context.WithCancel(context.TODO())
	masterCtx = ctx

	// Build ipfs nodes as specified by the global array of configurations
	SetupNodes(ctx)

	defer func() {
		fi, err := os.Create("mem.prof")
		if err != nil {
			panic(err)
		}
		pprof.WriteHeapProfile(fi)
		fi.Close()
	}()

	fi, err := os.Create("cpu.prof")
	if err != nil {
		panic(err)
	}
	defer fi.Close()

	pprof.StartCPUProfile(fi)
	defer pprof.StopCPUProfile()

	// Begin command execution
	fmt.Println("Enter a command:")
	for scan.Scan() {
		if len(scan.Text()) == 0 {
			continue
		}

		// ignore comments
		if len(scan.Text()) > 0 && scan.Text()[0] == '#' {
			continue
		}
		if scan.Text() == "==" {
			// Switch over input to standard in
			scan = bufio.NewScanner(os.Stdin)
			continue
		}
		if !RunCommand(scan.Text()) {
			return
		}
	}

	cancel()
	fmt.Println("Cleaning up and printing bandwidth(I/O)")
	/*
		for _, c := range controllers {
			globalStats.BwStats = append(globalStats.BwStats, c.GetStatistics())
		}

		gsjson, err := json.MarshalIndent(globalStats, "", "\t")
		if err != nil {
			panic(err)
		}
		fmt.Println(string(gsjson))
	*/

	if *ins {
		time.Sleep(time.Second * 2)
		panic("lets take a look at things.")
	}
}