main.go 1.83 KB
Newer Older
CedricPump's avatar
- init  
CedricPump committed
1
2
3
package main

import (
4
5
	"compress/gzip"
	"encoding/json"
CedricPump's avatar
- init  
CedricPump committed
6
	"fmt"
7
8
9
	"github.com/gorilla/mux"
	"io"
	"io/ioutil"
CedricPump's avatar
- init  
CedricPump committed
10
	"log"
11
12
13
	"net/http"
	"os"
	"path/filepath"
CedricPump's avatar
- init  
CedricPump committed
14
	"pvs_tsp/tspreader"
15
	"strings"
CedricPump's avatar
- init  
CedricPump committed
16
17
18
)

func main() {
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
71
72
73
	startServer(8000)
}

func startServer(port int)  {

	r := mux.NewRouter()

	r.HandleFunc("/readtsp", postTsp).Methods("POST")
	r.HandleFunc("/upload", getUpload).Methods("GET")

	http.ListenAndServe(fmt.Sprintf(":%d",port), r)
	log.Printf("server running on http://localhost:%d", port)
}

func getUpload(w http.ResponseWriter, r *http.Request)  {
	http.ServeFile(w, r, "./index.html")
}

func postTsp(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	// get file from Request
	file, handler, err := r.FormFile("tspspec")
	if err != nil {
		fmt.Println("Error reading file")
		fmt.Println(err)
		return
	}
	defer file.Close()

	filepath := fmt.Sprintf("./data/web/%s", handler.Filename)

	// Write File
	f, err := os.Create(filepath)
	fileBytes, err := ioutil.ReadAll(file)
	if err != nil {
		fmt.Println(err)
	}
	defer f.Close()
	f.Write(fileBytes)

	spec := readtsp(filepath)

	// Response
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(spec.String())
}

func readtsp(path string) *tspreader.TspSpec {

	if strings.HasSuffix(path,".gz") {
		_ = UnGzip(path, filepath.Dir(path))
	}

	spec, e := tspreader.Read(strings.TrimSuffix(path,".gz"))
CedricPump's avatar
- init  
CedricPump committed
74
75
76
	if e != nil {
		log.Fatal(e.Error())
	}
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103

	return spec
}


func UnGzip(source, target string) error {
	reader, err := os.Open(source)
	if err != nil {
		return err
	}
	defer reader.Close()

	archive, err := gzip.NewReader(reader)
	if err != nil {
		return err
	}
	defer archive.Close()

	target = filepath.Join(target, archive.Name)
	writer, err := os.Create(target)
	if err != nil {
		return err
	}
	defer writer.Close()

	_, err = io.Copy(writer, archive)
	return err
CedricPump's avatar
- init  
CedricPump committed
104
}