forked from bjssacademy/stackmachine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
56 lines (44 loc) · 1.27 KB
/
Copy pathmain.go
File metadata and controls
56 lines (44 loc) · 1.27 KB
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
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
func main() {
router := http.NewServeMux()
router.HandleFunc("GET /", rootHandler)
router.HandleFunc("POST /execute", executeCommand)
fmt.Println("server on port 8000")
err := http.ListenAndServe(":8000", CorsMiddleware(router))
if err != nil {
fmt.Println("error starting server", err)
}
}
func CorsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
next.ServeHTTP(w, r)
})
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("serving route /")
io.WriteString(w, "Stack machine API")
}
func executeCommand(w http.ResponseWriter, r *http.Request) {
fmt.Println("serving route /execute")
var command Command
err := json.NewDecoder(r.Body).Decode(&command)
if err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
result, machineErr := StackMachine(command.Text)
if machineErr != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(Result{Status: http.StatusBadRequest, ErrorMsg: machineErr.Error()})
return
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(Result{Status: http.StatusOK, Data: result})
}