Exemplo n.º 1
0
func (c *Cluster) doGET(w http.ResponseWriter, r *http.Request) {
	var err error

	// path is already read because we are using http.StripPrefix
	path := r.URL.Path

	if path == "" {
		http.NotFound(w, r)
		return
	}

	slave := c.getReadSlave()

	// this makes it easy to debug with curl -v
	w.Header().Add("X-RRPROXY-SERVER", slave.Addr)

	// get a redis client from the pool
	client, err := slave.Get()
	if err != nil {
		log.Error(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// make sure we return it
	defer slave.Put(client)

	var resp *redis.Resp

	// check to see if the key exists
	resp = client.Cmd("EXISTS", path)
	v, _ := resp.Int()

	if v == 0 {
		http.NotFound(w, r)
		return
	}

	// here we introduce some artifical latency. without it, and with redis
	// running on the same laptop as the server, other layers become the bottle
	// neck rather than redis, which kinda defeats the purpose of this lab
	if ForcedLatency > 0 {
		resp = client.Cmd("DEBUG", "sleep", ForcedLatency.Seconds())
		if resp.Err != nil {
			log.Fatal(resp.Err)
		}
	}

	// get the raw value as bytes and write it out
	resp = client.Cmd("GET", path)
	data, err := resp.Bytes()
	if err != nil {
		log.Error(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Write(data)
}