1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| func (p *HTTPPool) ServeHTTP(w http.ResponseWriter, r *http.Request) { if !strings.HasPrefix(r.URL.Path, p.basePath) { http.Error(w, "HTTPPool serving unexpected path: "+r.URL.Path, http.StatusBadRequest) return }
parts := strings.SplitN(r.URL.Path[len(p.basePath):], "/", 2) if len(parts) != 2 { http.Error(w, "bad request", http.StatusBadRequest) return }
groupName := parts[0] key := parts[1]
group := GetGroup(groupName) if group == nil { http.Error(w, "no such group:"+groupName, http.StatusBadRequest) return }
view, err := group.Get(key) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return }
body, err := proto.Marshal(&pb.Response{Value: view.ByteSlice()}) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/octet-stream") w.Write(body) }
func (h *HTTPGetter) Get(in *pb.Request, out *pb.Response) error { url := fmt.Sprintf("%s%s/%s", h.basePath, url.QueryEscape(in.GetGroup()), url.QueryEscape(in.GetKey()))
res, err := http.Get(url) if err != nil { return err } defer res.Body.Close()
if res.StatusCode != http.StatusOK { return fmt.Errorf("server status code: %v", res.StatusCode) }
data, err := ioutil.ReadAll(res.Body) if err != nil { return errors.New("read response body failed") }
if err = proto.Unmarshal(data, out); err != nil { return fmt.Errorf("decoding response body: %v", err) }
return nil }
|