Exemplo n.º 1
0
// How to use Revel properly with Defer Panic client library
func init() {
	dps := deferstats.NewClient("z57z3xsEfpqxpr0dSte0auTBItWBYa1c")

	go dps.CaptureStats()

	// Filters is the default set of global filters.
	revel.Filters = []revel.Filter{
		middleware.Wrapper(dps),
		revel.RouterFilter,            // Use the routing table to select the right Action
		revel.FilterConfiguringFilter, // A hook for adding or removing per-Action filters.
		revel.ParamsFilter,            // Parse parameters into Controller.Params.
		revel.SessionFilter,           // Restore and write the session cookie.
		revel.FlashFilter,             // Restore and write the flash cookie.
		revel.ValidationFilter,        // Restore kept validation errors and save new ones from cookie.
		revel.I18nFilter,              // Resolve the requested language
		HeaderFilter,                  // Add some security based headers
		revel.InterceptorFilter,       // Run interceptors around the action.
		revel.CompressFilter,          // Compress the result.
		revel.ActionInvoker,           // Invoke the action.
	}

	// register startup functions with OnAppStart
	// ( order dependent )
	// revel.OnAppStart(InitDB)
	// revel.OnAppStart(FillCache)

}
Exemplo n.º 2
0
// How to use Echo properly with Defer Panic client library
func main() {
	dps := deferstats.NewClient("z57z3xsEfpqxpr0dSte0auTBItWBYa1c")

	go dps.CaptureStats()

	// Echo instance
	e := echo.New()

	e.Use(middleware.Wrapper(dps))

	// Routes
	e.Get("/fast", func(c *echo.Context) error {
		return c.String(http.StatusOK, "Hello, world!\n")
	})

	e.Get("/slow", func(c *echo.Context) error {
		time.Sleep(5 * time.Second)
		return c.String(http.StatusOK, "Hello, world!\n")
	})

	e.Get("/panic", func(c *echo.Context) error {
		panic("There is no need for panic")
		return c.String(http.StatusOK, "Hello, world!\n")
	})

	// Start server
	e.Run(":3000")
}
Exemplo n.º 3
0
// How to use Martini properly with Defer Panic client library
func main() {
	dps := deferstats.NewClient("z57z3xsEfpqxpr0dSte0auTBItWBYa1c")

	go dps.CaptureStats()

	m := martini.New()
	r := martini.NewRouter()

	r.Get("/panic", func() string {
		panic("There is no need for panic")
		return "Hello world!"
	})
	r.Get("/slow", func() string {
		time.Sleep(5 * time.Second)
		return "Hello world!"
	})
	r.Get("/fast", func() string {
		return "Hello world!"
	})

	m.MapTo(r, (*martini.Routes)(nil))
	m.Action(r.Handle)

	m.Use(middleware.Wrapper(dps))

	m.RunOnAddr(":3000")
}
Exemplo n.º 4
0
func TestContextSOAHandler(t *testing.T) {
	deferstats.ResetHTTPStats()

	dps := deferstats.NewClient("token")

	mux := http.NewServeMux()
	post := ContextHandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		r.ParseForm()

		dpsi := r.Header.Get("X-dpparentspanid")
		okey := r.FormValue("other_key")

		if dpsi != "8103318854963911860" {
			t.Error("span not accessible")
		}
		if okey != "2" {
			t.Error("other_key not accessible")
		}
	})

	mux.Handle("/", NewWrapper(ContextHandlerFunc(post), dps))

	// set listener
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Error("http not listening")
	}

	dps.SetStatsURL("http://" + l.Addr().String() + "/")

	go http.Serve(l, mux)

	lurl := "http://" + l.Addr().String() + "/"

	data := url.Values{}
	data.Set("other_key", "2")

	client := &http.Client{}
	r, err := http.NewRequest("POST", lurl, bytes.NewBufferString(data.Encode()))
	if err != nil {
		panic(err)
	}
	r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
	r.Header.Add("X-dpparentspanid", "8103318854963911860")

	resp, err := client.Do(r)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	if len(deferstats.GetHTTPStats()) == 0 {
		t.Error("should have a http in the list")
	}

	if deferstats.GetHTTPStats()[0].ParentSpanId != 8103318854963911860 {
		t.Error("not tracking our parent_span_id")
	}
}
Exemplo n.º 5
0
func main() {

	dps := deferstats.NewClient("v00L0K6CdKjE4QwX5DL1iiODxovAHUfo")

	go dps.CaptureStats()

	http.HandleFunc("/zeus", dps.HTTPHandlerFunc(handler))
	http.ListenAndServe(":3000", nil)
}
Exemplo n.º 6
0
func main() {
	dps := deferstats.NewClient("z57z3xsEfpqxpr0dSte0auTBItWBYa1c")

	go dps.CaptureStats()

	http.Handle("/panic", middleware.NewWrapper(context.Background(), middleware.ContextHandlerFunc(panicHandler), dps))
	http.Handle("/slow", middleware.NewWrapper(context.Background(), middleware.ContextHandlerFunc(slowHandler), dps))
	http.Handle("/fast", middleware.NewWrapper(context.Background(), middleware.ContextHandlerFunc(fastHandler), dps))
	http.Handle("/spanId", middleware.NewWrapper(context.Background(), middleware.ContextHandlerFunc(spanIDHandler), dps))

	http.ListenAndServe(":3000", nil)
}
Exemplo n.º 7
0
func TestHTTPContextPostHandler(t *testing.T) {
	dps := deferstats.NewClient("token")

	mux := http.NewServeMux()
	post := ContextHandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			panic(err)
		}

		var tj TestContextJSON
		err = json.Unmarshal(body, &tj)
		if err != nil {
			panic(err)
		}
		if tj.Title != "sample title in json" {
			t.Error("not parsing the POST body correctly")
		}
	})
	mux.Handle("/", NewWrapper(ContextHandlerFunc(post), dps))

	// set listener
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Error("http not listening")
	}

	dps.SetStatsURL("http://" + l.Addr().String() + "/")

	go http.Serve(l, mux)

	lurl := "http://" + l.Addr().String() + "/"

	var jsonStr = []byte(`{"Title":"sample title in json"}`)
	req, err := http.NewRequest("POST", lurl, bytes.NewBuffer(jsonStr))
	if err != nil {
		panic(err)
	}
	req.Header.Set("X-Custom-Header", "some header")
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
}
Exemplo n.º 8
0
// How to use Logrus properly with Defer Panic client library
func main() {
	dps := deferstats.NewClient("z57z3xsEfpqxpr0dSte0auTBItWBYa1c")

	go dps.CaptureStats()

	log := logrus.New()

	hook, err := middleware.NewDPHook(dps)
	if err == nil {
		log.Hooks.Add(hook)
	}

	log.Error("Error is here!")

	log.Fatal("Fatal is here!")

	log.Panic("Panic is here!")
}
Exemplo n.º 9
0
// How to use Falcore properly with Defer Panic client library
func main() {
	dps := deferstats.NewClient("z57z3xsEfpqxpr0dSte0auTBItWBYa1c")

	go dps.CaptureStats()

	// create pipeline
	pipeline := falcore.NewPipeline()

	// add upstream pipeline stages
	var filter helloFilter
	pipeline.Upstream.PushBack(filter)

	// create server on port 0
	server := falcore.NewServer(0, pipeline)

	// start the server
	// this is normally blocking forever unless you send lifecycle commands
	http.ListenAndServe(":3000", middleware.Wrapper(dps, server))
}
Exemplo n.º 10
0
func TestHTTPContextHeaderHandler(t *testing.T) {
	dps := deferstats.NewClient("token")

	mux := http.NewServeMux()
	post := ContextHandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("X-Custom-Header") != "some header" {
			t.Error("headers not being passed through")
		}

		if r.Header.Get("Content-Type") != "application/json" {
			t.Error("headers not being passed through")
		}
	})
	mux.Handle("/", NewWrapper(ContextHandlerFunc(post), dps))

	// set listener
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Error("http not listening")
	}

	dps.SetStatsURL("http://" + l.Addr().String() + "/")

	go http.Serve(l, mux)

	lurl := "http://" + l.Addr().String() + "/"

	var jsonStr = []byte(`{"Title":"sample title in json"}`)
	req, err := http.NewRequest("POST", lurl, bytes.NewBuffer(jsonStr))
	if err != nil {
		panic(err)
	}
	req.Header.Set("X-Custom-Header", "some header")
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
}
Exemplo n.º 11
0
// How to use Gorilla properly with Defer Panic client library
func main() {
	dps := deferstats.NewClient("z57z3xsEfpqxpr0dSte0auTBItWBYa1c")

	go dps.CaptureStats()

	r := mux.NewRouter()

	r.HandleFunc("/slow", func(w http.ResponseWriter, r *http.Request) {
		time.Sleep(5 * time.Second)
		w.Write([]byte("Hello, world!"))
	})

	r.HandleFunc("/fast", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello, world!"))
	})

	r.HandleFunc("/panic", func(w http.ResponseWriter, r *http.Request) {
		panic("There is no need for panic")
		w.Write([]byte("Hello, world!"))
	})

	http.ListenAndServe(":3000", middleware.Wrapper(dps, r))
}
Exemplo n.º 12
0
func init() {
	parseJsonFile("etc/config.json", &Config)
	analyticsCode = getDefaultCode(Config.AnalyticsFile)
	configGithubAuth()

	if Config.DB == "" {
		fmt.Println("数据库地址还没有配置,请到config.json内配置db字段.")
		os.Exit(1)
	}

	session, err := mgo.Dial(Config.DB)
	if err != nil {
		panic(err)
		fmt.Println("MongoDB连接失败:", err.Error())
		os.Exit(1)
	}

	session.SetMode(mgo.Monotonic, true)

	db := session.DB("gopher")

	store = sessions.NewCookieStore([]byte(Config.CookieSecret))

	utils = &Utils{}

	// 如果没有status,创建
	var status Status
	c := db.C(STATUS)
	err = c.Find(nil).One(&status)

	if err != nil {
		c.Insert(&Status{
			Id_:        bson.NewObjectId(),
			UserCount:  0,
			TopicCount: 0,
			ReplyCount: 0,
			UserIndex:  0,
		})
	}

	// 检查是否有超级账户设置
	var superusers []string
	for _, username := range strings.Split(Config.Superusers, ",") {
		username = strings.TrimSpace(username)
		if username != "" {
			superusers = append(superusers, username)
		}
	}

	if len(superusers) == 0 {
		fmt.Println("你没有设置超级账户,请在config.json中的superusers中设置,如有多个账户,用逗号分开")
	}

	c = db.C(USERS)
	var users []User
	c.Find(bson.M{"issuperuser": true}).All(&users)

	// 如果mongodb中的超级用户不在配置文件中,取消超级用户
	for _, user := range users {
		if !stringInArray(superusers, user.Username) {
			c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{"issuperuser": false}})
		}
	}

	// 设置超级用户
	for _, username := range superusers {
		c.Update(bson.M{"username": username, "issuperuser": false}, bson.M{"$set": bson.M{"issuperuser": true}})
	}

	// 生成users.json字符串
	generateUsersJson(db)

	if Config.DeferPanicApiKey != "" {
		dps = deferstats.NewClient(Config.DeferPanicApiKey)
	}

	ACCESS_KEY = Config.QiniuAccessKey
	SECRET_KEY = Config.QiniuSecretKey
}
Exemplo n.º 13
0
func main() {
	var (
		port          = 3001
		redisDatabase = 0
		redisPoolSize = 10
		clientID      = ""
		clientSecret  = ""
		hashKey       = "randomishstringthatsi32charslong"
		blockKey      = "randomishstringthatsi32charslong"
		deferPanicKey = ""
	)
	flag.IntVar(&port, "port", port, "Port to start the server on")
	flag.IntVar(&procs, "procs", 1, "Number of CPU processors (0 to use max)")
	flag.BoolVar(&debug, "debug", false, "Debug mode")
	flag.StringVar(
		&redisURL, "redisURL", redisURL,
		"Redis URL to tcp connect to")
	flag.StringVar(
		&staticPrefix, "staticPrefix", staticPrefix,
		"Prefix in front of static assets in HTML")
	flag.IntVar(&redisDatabase, "redisDatabase", redisDatabase,
		"Redis database number to connect to")
	flag.StringVar(
		&clientID, "clientID", clientID,
		"OAuth Client ID")
	flag.StringVar(
		&clientSecret, "clientSecret", clientSecret,
		"OAuth Client Secret")
	flag.BoolVar(&usingHTTPS, "usingHTTPS", usingHTTPS,
		"Whether requests are made under HTTPS")
	flag.StringVar(
		&hashKey, "hashKey", hashKey,
		"HMAC hash key to use for encoding cookies")
	flag.StringVar(
		&blockKey, "blockKey", blockKey,
		"Block key to encrypt cookie values")
	flag.StringVar(
		&deferPanicKey, "deferPanicKey", deferPanicKey,
		"Auth key for deferpanic.com")
	flag.Parse()

	dfs := deferstats.NewClient(deferPanicKey)
	if deferPanicKey == "" {
		dfs.SetnoPost(true)
	}
	go dfs.CaptureStats()

	oauthConf.ClientID = clientID
	oauthConf.ClientSecret = clientSecret

	sCookie = securecookie.New([]byte(hashKey), []byte(blockKey))

	log.Println("REDIS DATABASE:", redisDatabase)
	log.Println("DEBUG MODE:", debug)
	log.Println("STATIC PREFIX:", staticPrefix)

	if !debug {
		redisPoolSize = 100
	}

	// Figuring out how many processors to use.
	maxProcs := runtime.NumCPU()
	if procs == 0 {
		procs = maxProcs
	} else if procs < 0 {
		panic("PROCS < 0")
	} else if procs > maxProcs {
		panic(fmt.Sprintf("PROCS > max (%v)", maxProcs))
	}
	log.Println("PROCS:", procs)
	runtime.GOMAXPROCS(procs)

	renderer = render.New(render.Options{
		IndentJSON:    debug,
		IsDevelopment: debug,
	})

	df := func(network, addr string) (*redis.Client, error) {
		client, err := redis.Dial(network, addr)
		if err != nil {
			return nil, err
		}
		err = client.Cmd("SELECT", redisDatabase).Err
		if err != nil {
			return nil, err
		}
		// if err = client.Cmd("AUTH", "SUPERSECRET").Err; err != nil {
		// 	client.Close()
		// 	return nil, err
		// }
		return client, nil
	}

	var err error
	redisPool, err = pool.NewCustomPool("tcp", redisURL, redisPoolSize, df)
	errorHandler(err)

	mux := mux.NewRouter()
	mux.HandleFunc("/", dfs.HTTPHandler(indexHandler)).Methods("GET", "HEAD")
	mux.HandleFunc("/v1/ping", dfs.HTTPHandler(pingHandler)).Methods("GET", "HEAD")
	mux.HandleFunc("/v1", dfs.HTTPHandler(fetchHandler)).Methods("GET", "HEAD")
	mux.HandleFunc("/v1", dfs.HTTPHandler(updateHandler)).Methods("POST", "PUT")
	mux.HandleFunc("/v1", dfs.HTTPHandler(deleteHandler)).Methods("DELETE")
	mux.HandleFunc("/v1/stats", dfs.HTTPHandler(privateStatsHandler)).Methods("GET")
	mux.HandleFunc("/v1/flush", dfs.HTTPHandler(flushHandler)).Methods("DELETE")
	mux.HandleFunc("/v1/bulk", dfs.HTTPHandler(bulkHandler)).Methods("POST", "PUT")
	mux.HandleFunc("/login", dfs.HTTPHandler(handleGitHubLogin)).Methods("GET")
	mux.HandleFunc("/logout", dfs.HTTPHandler(logoutHandler)).Methods("GET", "POST")
	mux.HandleFunc("/github_oauth_cb", dfs.HTTPHandler(handleGitHubCallback)).Methods("GET")
	mux.HandleFunc("/domainkeys/new", domainkeyNewHandler).Methods("POST")
	mux.HandleFunc("/domainkeys/delete", domainkeyDeleteHandler).Methods("POST")

	n := negroni.Classic()

	n.UseHandler(mux)
	n.Run(fmt.Sprintf(":%d", port))
}
Exemplo n.º 14
0
// NewLogger configures defer panic error and starts capturing stats.
// It looks for DEFERPANIC_KEY,
// DEVERPANIC_ENVIRONMENT and DEFERPANIC_APPGROUP environment vars
func NewLogger() {
	dfs = deferstats.NewClient(os.Getenv("DEFERPANIC_API_KEY"))
	dfs.Setenvironment(os.Getenv("DEFERPANIC_ENVIRONMENT"))
	dfs.SetappGroup(os.Getenv("DEFERPANIC_APPGROUP"))
	go dfs.CaptureStats()
}