-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
116 lines (97 loc) · 2.65 KB
/
main.go
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"onlineboard/src/boardlist"
"strconv"
"time"
"github.com/gorilla/mux"
)
type CreateLineMessage struct {
Parent int `json:"parent"`
Value json.RawMessage `json:"value"`
}
func main() {
r := mux.NewRouter()
bl := boardlist.New()
r.HandleFunc(`/`, func(writer http.ResponseWriter, request *http.Request) {
http.ServeFile(writer, request, "./dist/index.html")
})
r.Methods("GET").Path("/board/{boardid}").HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
if bl.ExistBoard(mux.Vars(request)["boardid"]) {
http.ServeFile(writer, request, "./dist/board.html")
} else {
http.Redirect(writer, request, "/", 303)
}
})
r.HandleFunc("/new", func(w http.ResponseWriter, r *http.Request) {
boardid := bl.CreateBoard()
http.Redirect(w, r, "/board/"+boardid, 303)
})
r.HandleFunc("/board/{boardid}/socket", bl.MakeEchoSocket())
r.Methods("POST").Path("/board/load").HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
var msg []json.RawMessage
err = json.Unmarshal(b, &msg)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
boardid := bl.LoadBoard(msg)
http.Redirect(w, r, "/board/"+boardid, 303)
})
r.Methods("POST").Path("/board/{boardid}/line").HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
var msg CreateLineMessage
err = json.Unmarshal(b, &msg)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
output, err := bl.CreateLine(mux.Vars(r)["boardid"], msg.Parent, msg.Value)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
w.Write([]byte(strconv.Itoa(output)))
})
r.Methods("DELETE").Path("/board/{boardid}/line/{lineid}").HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
mapa := mux.Vars(r)
boardid := mapa["boardid"]
strlineid := mapa["lineid"]
lineid, err := strconv.Atoi(strlineid)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
err = bl.DeleteLine(boardid, lineid)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
})
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./dist")))
srv := &http.Server{
Handler: r,
Addr: "0.0.0.0:3000",
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}