示例#1
0
文件: raft.go 项目: QLeelulu/goatherd
func (this *electServer) Router(w http.ResponseWriter, r *http.Request) {
	var err error
	switch r.URL.Path {
	case "/join":
		err = this.doJoin(r)
	case "/peers":
		err = json.NewEncoder(w).Encode(this.doPeers())
	case "/leader":
		err = json.NewEncoder(w).Encode(this.doLeader())
	case "/peer_config":
		err = json.NewEncoder(w).Encode(this.doPeerConfig())
	case "/peer_exchange":
		err = this.doExchangePeerConfig(r, w)
	case "/stat":
		err = this.doStat(w)
	default:
		resp := web.ApiResponse{404, "NOT_FOUND", nil}
		resp.Write(w)
	}
	if err != nil {
		resp := web.ApiResponse{502, err.Error(), nil}
		resp.Write(w)
		log.Errorf("%s handel faild : %s", r.URL.Path, err.Error())
	}
}
示例#2
0
func (this *httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	peers := this.elect.doPeers()

	// get peers
	var ret = web.ApiResponse{200, "ok", nil}
	var collies = make(PeerConfigMap)
	if len(r.URL.Query()["collie"]) == 0 {
		collies = peers
	} else {
		for _, collie := range r.URL.Query()["collie"] {
			if peer, ok := peers[collie]; ok {
				collies[collie] = peer
			} else {
				ret.Set(collie, web.ApiResponse{500, "collie unvalaible : " + collie, nil})
			}
		}
	}

	for name, peer := range collies {
		if name == this.Name {
			ret.Set(name, this.router(r))
		} else {
			query := r.URL.Query()
			query["collie"] = []string{name}
			resps := this.proxy(fmt.Sprintf("http://%s%s?%s", peer.HttpAddr, r.URL.Path, query.Encode()), r.Body)
			if _, ok := resps.Data.(map[string]interface{}); ok {
				for name, resp := range resps.Data.(map[string]interface{}) {
					ret.Set(name, resp)
				}
			} else {
				log.Errorf("bad format : %+v", reflect.TypeOf(resps.Data))
			}
		}

	}
	ret.Write(w)
}