Find the frontend files by using the server's path.
[armadillo.git] / src / server.go
1 package server
2
3 import (
4 "fmt"
5 "http"
6 "io"
7 "json"
8 "os"
9 "path"
10 "./paths"
11 )
12
13 var dir, file = path.Split(path.Clean(os.Getenv("_")))
14 var kFrontEndFiles string = path.Join(dir, "fe")
15
16 func indexHandler(connection *http.Conn, request *http.Request) {
17 fd, err := os.Open(path.Join(kFrontEndFiles, "index.html"), os.O_RDONLY, 0)
18 if err != nil {
19 fmt.Print("Error opening file ", err.String(), "\n")
20 return
21 }
22 io.Copy(connection, fd)
23 }
24
25 func serviceHandler(connection *http.Conn, request *http.Request) {
26 if request.Method != "POST" {
27 io.WriteString(connection, "Error: Not a POST request")
28 return
29 }
30
31 switch request.FormValue("action") {
32 case "list":
33 files, err := paths.List(request.FormValue("path"))
34 if err != nil {
35 errorResponse(connection, err.String())
36 } else {
37 okResponse(connection, files)
38 }
39 return
40 }
41
42 errorResponse(connection, "Unhandled action")
43 }
44
45 func errorResponse(connection *http.Conn, message string) {
46 response := map[string] string {
47 "error": "-1",
48 "message": message,
49 }
50 json_data, err := json.Marshal(response)
51
52 connection.SetHeader("Content-Type", "text/json")
53 if err != nil {
54 io.WriteString(connection, "{\"error\":\"-9\",\"message\":\"Internal encoding error\"}")
55 } else {
56 connection.Write(json_data)
57 }
58 }
59
60 func okResponse(connection *http.Conn, data interface{}) {
61 connection.SetHeader("Content-Type", "text/json")
62 json_data, err := json.Marshal(data)
63 if err != nil {
64 errorResponse(connection, "Internal encoding error")
65 } else {
66 connection.Write(json_data)
67 }
68 }
69
70 func RunFrontEnd() {
71 mux := http.NewServeMux()
72 mux.HandleFunc("/", indexHandler)
73 mux.Handle("/fe/", http.FileServer(kFrontEndFiles, "/fe/"))
74 mux.HandleFunc("/service", serviceHandler)
75
76 error := http.ListenAndServe(":8084", mux)
77 fmt.Printf("error %v", error)
78 }