Example #1
0
func handleConn(w http.ResponseWriter, r *http.Request) {
	log.Println(r.URL)

	password := ""  // no password set
	db := int64(-1) // use default DB
	client := redis.NewTCPClient("localhost:6379", password, db)
	defer client.Close()

	host := r.Header.Get("x-host")
	token := strings.Split(host, ".")[0]
	route := client.SRandMember("route::" + token)

	log.Println(token)
	log.Println(route.Val())

	remote, err := url.Parse(route.Val())
	if err != nil {
		panic(err)
	}

	proxy := httputil.NewSingleHostReverseProxy(remote)

	r.Header.Add("X-Proxy", "just-in-the-neighborhood-and-thought-i-would-drop-in")
	r.Header.Add("X-Articulated-Route", route.Val())
	r.Header.Add("X-Token", token)

	proxy.ServeHTTP(w, r)
}
Example #2
0
// Creates a new ESPubSub handler.
func New(redisHost, redisPassword string, redisDb int64) ESPubSub {
	s := new(chanCollection)
	s.channels = map[string]channel{}

	s.redisClient = redis.NewTCPClient(redisHost, redisPassword, redisDb)
	return s
}
Example #3
0
// Creat new Redis connection manager
func (si *System) RedisConnect() *RedisManager {
	addr := fmt.Sprintf(
		"%s:%d",
		si.Config.Redis.Host,
		si.Config.Redis.Port,
	)
	pw := si.Config.Redis.Password

	rm := RedisManager{map[string]*redis.Client{}}
	rm.DbConnect["bfs"] = redis.NewTCPClient(addr, pw, si.Config.Redis.BFSDb)
	rm.DbConnect["auth"] = redis.NewTCPClient(addr, pw, si.Config.Redis.AuthDb)
	rm.DbConnect["ext"] = redis.NewTCPClient(addr, pw, si.Config.Redis.ExtDb)
	rm.DbConnect["upload"] = redis.NewTCPClient(addr, pw, si.Config.Redis.UploadDb)

	return &rm
}
Example #4
0
func getRedisConn() *redis.Client {
	if redisConn == nil {
		redisConn := redis.NewTCPClient(redisConfig.Host, redisConfig.Password, redisConfig.DB)
		defer redisConn.Close()
		return redisConn
	}
	return redisConn
}
Example #5
0
func ExampleCustomCommand() {
	client := redis.NewTCPClient(":6379", "", -1)
	defer client.Close()

	get := Get(client, "key_does_not_exist")
	fmt.Println(get.Err(), get.Val())
	// Output: (nil)
}
Example #6
0
func getRedisConn() *redis.Client {
	if redisConn == nil {
		redisConn := redis.NewTCPClient(redisConfig.Host, redisConfig.Password, redisConfig.DB)
		redisConn.ConnPool.(*redis.MultiConnPool).MaxCap = redisConfig.ConnPoolSize
		defer redisConn.Close()
		return redisConn
	}
	return redisConn
}
Example #7
0
func ExampleTCPClient() {
	password := ""  // no password set
	db := int64(-1) // use default DB
	client := redis.NewTCPClient("localhost:6379", password, db)
	defer client.Close()

	ping := client.Ping()
	fmt.Println(ping.Err(), ping.Val())
	// Output: <nil> PONG
}
Example #8
0
// NewRedisClient connects to redis after ensuring that the server is
// indeed running.
func NewRedisClient(addr, password string, database int64) (*redis.Client, error) {
	// Bug #97459 -- is the redis client library faking connection for
	// the down server?
	conn, err := net.Dial("tcp", addr)
	if err != nil {
		return nil, err
	}
	conn.Close()

	return redis.NewTCPClient(addr, password, database), nil
}
Example #9
0
func setup(t *testing.T) *testEnv {
	// comment out below to see logging
	log.SetOutput(ioutil.Discard)

	t.Log("creating a test env")
	e := new(testEnv)
	e.s = New(":6379", "", -1)
	e.redis = redis.NewTCPClient(":6379", "", 6)
	e.server = httptest.NewServer(e.s)
	return e
}
Example #10
0
func ExampleSetGet() {
	client := redis.NewTCPClient(":6379", "", -1)
	defer client.Close()

	set := client.Set("foo", "bar")
	fmt.Println(set.Err(), set.Val())

	get := client.Get("foo")
	fmt.Println(get.Err(), get.Val())

	// Output: <nil> OK
	// <nil> bar
}
Example #11
0
func (p *Persistor) getRedis() *redis.Client {
	// Guard in case someone else is opening Redis
	redisAddr := "localhost:6379"
	m := sync.Mutex{}
	m.Lock()
	if !p.connected {
		log.Printf("[Persistor] Opening Redis at [%v]\n", redisAddr)
		p.redis = redis.NewTCPClient(redisAddr, "", 0)
		p.connected = true
	}
	m.Unlock()
	return p.redis
}
Example #12
0
func InitTests() {
	server = httptest.NewServer(createRouter())
	connectToRedis = func() *redis.Client {
		// CONFIGURE THIS!
		password := ""
		client := redis.NewTCPClient("localhost:6379", password, 1)
		return client
	}
	client := connectToRedis()
	defer client.Close()
	client.FlushDb()
	// Bootstrap the system, with an admin
	hash, _ := bcrypt.Hash("asdf")
	client.HMSet("user:admin", "isadmin", "1", "password", hash)
}
func main() {

	password := ""  // no password set
	db := int64(-1) // use default DB
	client := redis.NewTCPClient("localhost:6379", password, db)

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		log.Println("incoming request ", r.Header.Get("x-token"))
		hostname, err := os.Hostname()
		when := time.Now().Format("Mon Jan 2 15:04:05 -0700 MST 2006")
		if err != nil {
			fmt.Printf("error: ", err)
			return
		}

		fmt.Fprintf(w, "   _____       _                    \n")
		fmt.Fprintf(w, "  / ____|     | |                   \n")
		fmt.Fprintf(w, " | |  __  ___ | | __ _ _ __   __ _  \n")
		fmt.Fprintf(w, " | | |_ |/ _ \\| |/ _` | '_ \\ / _` | \n")
		fmt.Fprintf(w, " | |__| | (_) | | (_| | | | | (_| | \n")
		fmt.Fprintf(w, "  \\_____|\\___/|_|\\__,_|_| |_|\\__, | \n")
		fmt.Fprintf(w, "                              __/ | \n")
		fmt.Fprintf(w, "                             |___/  \n\n")

		token := r.Header.Get("x-token")
		members := client.SMembers("route::" + token)
		vals := members.Val()
		fmt.Fprintf(w, strings.Join(vals, ", "))

		fmt.Fprintf(w, "\nHello World\n")
		fmt.Fprintf(w, "Path->%s\n", html.EscapeString(r.URL.Path))
		fmt.Fprintf(w, "Golang %s\n", runtime.Version())
		fmt.Fprintf(w, "%s %s %s %s %d %s\n", runtime.GOOS, hostname, runtime.Version(), when, runtime.NumCPU(), runtime.GOARCH)
		fmt.Fprintf(w, "headers->\n")
		keys := make([]string, 0)
		for it := range r.Header {
			keys = append(keys, it)
		}
		sort.Strings(keys)
		for it := range keys {
			fmt.Fprintf(w, "%s: %s\n", keys[it], r.Header.Get(keys[it]))
		}

	})

	log.Fatal(http.ListenAndServe(":31338", nil))
}
Example #14
0
func ExamplePipeline() {
	client := redis.NewTCPClient(":6379", "", -1)
	defer client.Close()

	var set *redis.StatusReq
	var get *redis.StringReq
	reqs, err := client.Pipelined(func(c *redis.PipelineClient) {
		set = c.Set("key1", "hello1")
		get = c.Get("key2")
	})
	fmt.Println(err, reqs)
	fmt.Println(set)
	fmt.Println(get)
	// Output: <nil> [SET key1 hello1: OK GET key2: (nil)]
	// SET key1 hello1: OK
	// GET key2: (nil)
}
Example #15
0
func NewTracker(redisAddress string) (tracker *Tracker, err error) {
	password := "" // no password set
	conn := redis.NewTCPClient(redisAddress, password, -1)

	defer conn.Close()

	tracker = &Tracker{
		Conn:     conn,
		Notifier: make(data.EventsChannel, 1),
		Funnels:  make(data.EventsChannel, 1),
	}

	go tracker.listenForPageviews()
	go tracker.listenForFunnels()

	return
}
Example #16
0
func ExampleTransaction() {
	client := redis.NewTCPClient(":6379", "", -1)
	defer client.Close()

	client.Del("key")

	multi, err := client.MultiClient()
	_ = err
	defer multi.Close()

	watch := multi.Watch("key")
	_ = watch.Err()

	reqs, err := transaction(multi)
	fmt.Println(err, reqs)

	// Output: <nil> [SET key 1: OK]
}
Example #17
0
func main() {
	var redisAddr = flag.String("redis-addr", "localhost:6379", "redis address")
	var redisPass = flag.String("redis-pass", "", "redis password")
	var redisDb = flag.Int("redis-db", 0, "redis database number")
	var urlPrefix = flag.String("url-prefix", "channel", "URL prefix")
	var listenAddr = flag.String("listen-addr", "localhost:8080", "listen address")
	var allowPosts = flag.Bool("allow-posts", true, "allow POSTing to the queue")
	var keepAlive = flag.Int("keepalive", 10, "seconds between keep-alive messages (0 to disable")
	var clientRetry = flag.Float64("client-retry", 3600*24, "seconds for the client to wait before reconnecting (0 to use browser defaults)")

	flag.Parse()

	log.Print("Redis Address  : ", *redisAddr)
	log.Print("Redis Password : "******"Redis Database : ", *redisDb)
	log.Print("URL Prefix     : ", *urlPrefix)
	log.Print("Listen Address : ", *listenAddr)
	log.Print("Allow POSTs    : ", *allowPosts)
	log.Print("Keep-Alive     : ", *keepAlive)

	if *clientRetry > 0.0 {
		log.Print("Client Retry   : ", *clientRetry)
		clientRetryTime = strconv.Itoa(int(*clientRetry * 1000.0))
	}

	keepAliveTime = time.Duration(*keepAlive)

	client = redis.NewTCPClient(*redisAddr, *redisPass, int64(*redisDb))
	defer client.Close()

	router := mux.NewRouter()
	subroute := router.PathPrefix(fmt.Sprintf("/%s/", *urlPrefix)).Subrouter()
	subroute.HandleFunc("/{queue}", subscriber).Methods("GET")
	if *allowPosts {
		subroute.HandleFunc("/{queue}", publisher).Methods("POST")
	}

	err := http.ListenAndServe(*listenAddr, router)
	if err != nil {
		log.Fatal("http.ListenAndServe:", err)
	}
}
Example #18
0
func initRedis(addr string, db int64, pw string) {
	rds = redis.NewTCPClient(addr, pw, db)

	ret := rds.ScriptLoad(`
		local key, value, maxlength = KEYS[1], ARGV[1], tonumber(ARGV[2])
		if not maxlength then
			return {err = "INVALID ARGUMENTS"}
		end
		
		redis.call("RPUSH", key, value)
		local listlength = redis.call("LLEN", key)
		
		if listlength >= maxlength then
			local start = listlength - maxlength
			redis.call("LTRIM", key, start, maxlength)
		end
	`)
	rdsCircularBufferHash = ret.Val()

}
Example #19
0
func Init() {
	srvAddr := "localhost:6379"

	Redis = r.NewTCPClient(srvAddr, "", -1)

	tcpAddr, _ := net.ResolveTCPAddr("tcp", srvAddr)

	if _, err := net.DialTCP("tcp", nil, tcpAddr); err != nil {
		fmt.Printf(" [NOTICE]\tRedis server not connected.\n")
		fmt.Printf(" [NOTICE]\tAttempting to boot up Redis server.\n")

		response := make(chan bool, 1)

		go bootRedisServer(response)

		<-response
		fmt.Printf(" [NOTICE]\tRedis server has connected.\n")
	}

	// clear stale data
	Redis.FlushDb()
}
Example #20
0
func ExamplePubSub() {
	client := redis.NewTCPClient(":6379", "", -1)
	defer client.Close()

	pubsub, err := client.PubSubClient()
	defer pubsub.Close()

	ch, err := pubsub.Subscribe("mychannel")
	_ = err

	subscribeMsg := <-ch
	fmt.Println(subscribeMsg.Err, subscribeMsg.Name)

	pub := client.Publish("mychannel", "hello")
	_ = pub.Err()

	msg := <-ch
	fmt.Println(msg.Err, msg.Message)

	// Output: <nil> subscribe
	// <nil> hello
}
Example #21
0
func New(host string, password string, db int64, list string) Log {
	return Log{
		client: redis.NewTCPClient(host, password, db),
		List:   list,
	}
}
Example #22
0
		var buf string
		e := websocket.Message.Receive(ws, &buf)
		if e != nil {
			fmt.Println(e)
			break
		}

		e = websocket.Message.Send(ws, buf)
		if e != nil {
			fmt.Println(e)
			break
		}
	}
}

var rds *redis.Client = redis.NewTCPClient("localhost:6379", "", 0)

func main() {
	defer rds.Close()
	router := mux.NewRouter()
	fmt.Println(rds)
	router.HandleFunc("/", handler)
	router.HandleFunc("/static/{path:.*}", staticHandler)
	router.HandleFunc("/post", newPostHandler).Methods("POST")
	router.HandleFunc("/post", getPostsHandler).Methods("GET")
	router.HandleFunc("/post/{id}/comments", newCommentHandler)
	router.HandleFunc("/post/{id}", postHandler)
	router.Handle("/ws/", websocket.Handler(websocket_handler))
	http.ListenAndServe(":8000", router)
}
Example #23
0
package main

import (
	"fmt"
	"github.com/vmihailenco/redis"
	"net/http"
	//	"regexp"
	"github.com/gorilla/mux"
	"github.com/jameskeane/bcrypt"
)

var connectToRedis = func() *redis.Client {
	password := "" // no password set
	return redis.NewTCPClient("localhost:6379", password, -1)
}

func getSecret(user, realm string) string {
	client := connectToRedis()
	defer client.Close()
	return client.HMGet("user:"******"password").Val()[0].(string)
}

func checkAdm(auth *Basic) bool {
	if auth != nil {
		client := connectToRedis()
		defer client.Close()
		if checkUserPass(auth.Username, auth.Password, client) {
			if client.HGet("user:"******"isadmin").Val() == "1" {
				return true
			}
		}