func TestMemcache(t *testing.T) { airfields := []airfield.Airfield{ airfield.Airfield{ID: "MockID", ShortName: "MockShortName", Name: "MockName", Region: "FR", ICAO: "AAAA", Flags: 0, Catalog: 11, Length: 1000, Elevation: 2000, Runway: "32R", Frequency: 123.45, Latitude: 32.533, Longitude: 100.376}, } // get the expected geojson to compare at the end geojson, _ := spatial.Struct2GeoJSON([]interface{}{ airfields[0], }) expected, _ := json.MarshalIndent(geojson, "", "\t") // using a mock object to return airfields mock := &mock.Mock{ GetAirfieldF: func(regions []string, updatedSince time.Time) ([]airfield.Airfield, error) { return airfields, nil }, } // use a local memcached server cfg := Config{Airfielder: mock, Waypointer: mock, Static: "/tmp", Memcache: "localhost:11211"} srv, err := NewServer(cfg) if err != nil { t.Errorf("failed to init server with memcache :: %v", err) return } resp := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/airfield/", nil) req.Header.Set("Accept", "application/json") srv.mux.ServeHTTP(resp, req) r, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("failed to read response :: %v", err) return } // first we compare the reply with the expected json if string(r) != string(expected) { t.Errorf("reply expected %v but got %v", string(expected), string(r)) return } // then we compare the value in memcache with the expected json mclient := memcache.New(cfg.Memcache) a, err := mclient.Get(NewCacheResponseWriter(nil, nil, nil).requestKey(req)) if err != nil { t.Errorf("failed to contact memcache :: %v", err) return } if string(a.Value) != string(expected) { t.Errorf("memcache expected %v but got %v", string(expected), string(a.Value)) return } }
// toOutput returns a string representation (in the requested format) of the given content. // format should be as in the Accept: header (application/json, ...), content is an array // of Struct which can be Airfield, Waypoint, etc. func (srv *Server) toOutput(format string, content []interface{}) (string, error) { var output string switch format { case "application/json": collection, err := spatial.Struct2GeoJSON(content) if err != nil { return "", err } bytes, _ := json.MarshalIndent(collection, "", "\t") output = string(bytes) //case "application/csv": FIXME: enable csv output //output = util.Struct2CSV(content) default: return "", fmt.Errorf("format %v not supported", format) } return output, nil }