Ejemplo n.º 1
0
func saveGraphHandler(fs iFileSystem) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		filename := "graphs/" + mux.Vars(r)["id"] + ".json"
		if _, err := fs.Stat(filename); fs.IsNotExist(err) {
			w.WriteHeader(http.StatusNotFound)
			return
		}
		pwFilename := "passwords/" + mux.Vars(r)["id"] + ".txt"
		if _, err := fs.Stat(pwFilename); fs.IsNotExist(err) {
			w.WriteHeader(http.StatusNotFound)
			return
		}
		pw, _ := ioutil.ReadFile(pwFilename)
		if strings.Compare(string(pw), mux.Vars(r)["pw"]) != 0 {
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
		newGraph, err := ioutil.ReadAll(r.Body)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		err = ioutil.WriteFile(filename, newGraph, 0644)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}

		graph, err := p.CreateGraphFromFile(filename)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}

		// Potential bottleneck draining memory, making sure only one graph is routed at any moment.
		// Should add timing in log if it takes > 1s? 10s?
		mutex.Lock()
		result := a.Route(graph)
		mutex.Unlock()
		js, err := p.CreateJSONFromRoutedPath(result)
		w.Header().Set("Content-Type", "application/json")
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		_, err = w.Write(js)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
	}
}
Ejemplo n.º 2
0
// TestAllFiles goes through tests/ folder and tries to route a path, verifying towards files
// in validations/ folder. Folder structure is the same in both tests/ and validations/ to
// know which validation belongs to which test case.
func TestAllFiles(t *testing.T) {
	for _, testPath := range getDirFileNames(t, "tests/") {
		graph, err := parser.CreateGraphFromFile(testPath)
		if err != nil {
			failAndPrint(t, err.Error())
		}
		validation, err := os.Open("validations/" + testPath[6:])
		defer func() {
			if closeErr := validation.Close(); closeErr != nil && err == nil {
				failAndPrint(t, closeErr.Error())
			}
		}()
		if err != nil {
			assertFailingPath(t, graph, testPath)
			continue
		}
		var path []string
		scanner := bufio.NewScanner(validation)
		for scanner.Scan() {
			path = append(path, scanner.Text())
		}
		assertCorrectPath(t, path, Route(graph), testPath)
	}
}