-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathapp.go
175 lines (138 loc) · 5.79 KB
/
app.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
glog "log"
"os/signal"
"syscall"
"time"
"net/http"
"os"
"github.com/zasper-io/zasper/content"
"github.com/zasper-io/zasper/core"
"github.com/zasper-io/zasper/gitclient"
"github.com/zasper-io/zasper/health"
"github.com/zasper-io/zasper/kernel"
"github.com/zasper-io/zasper/kernelspec"
"github.com/zasper-io/zasper/search"
"github.com/zasper-io/zasper/session"
"github.com/zasper-io/zasper/websocket"
"github.com/rs/zerolog"
"github.com/gorilla/mux"
"github.com/rs/cors"
)
// Response structure to return as JSON
type InfoResponse struct {
ProjectName string `json:"project"`
UserName string `json:"username"`
OS string `json:"os"`
}
func InfoHandler(w http.ResponseWriter, r *http.Request) {
response := InfoResponse{
ProjectName: core.Zasper.ProjectName,
UserName: core.Zasper.UserName,
OS: core.Zasper.OSName,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(response)
}
func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
debug := flag.Bool("debug", false, "sets log level to debug")
cwd := flag.String("cwd", ".", "base directory of project")
port := flag.String("port", ":8048", "port to start the server on")
flag.Parse()
zerolog.SetGlobalLevel(zerolog.InfoLevel)
if *debug {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
}
router := mux.NewRouter()
core.Zasper = core.SetUpZasper(*cwd)
core.ZasperSession = core.SetUpActiveSessions()
kernel.ZasperPendingKernels = kernel.SetUpStateKernels()
kernel.ZasperActiveKernels = kernel.SetUpStateKernels()
kernel.ProtocolVersion = "8.6.2"
// API routes
apiRouter := router.PathPrefix("/api").Subrouter()
apiRouter.HandleFunc("/health", health.HealthCheckHandler).Methods("GET")
apiRouter.HandleFunc("/info", InfoHandler).Methods("GET")
// contents
apiRouter.HandleFunc("/contents/create", content.ContentCreateAPIHandler).Methods("POST")
apiRouter.HandleFunc("/contents", content.ContentAPIHandler).Methods("POST")
apiRouter.HandleFunc("/contents", content.ContentUpdateAPIHandler).Methods("PUT")
apiRouter.HandleFunc("/contents/rename", content.ContentRenameAPIHandler).Methods("POST")
apiRouter.HandleFunc("/contents", content.ContentDeleteAPIHandler).Methods("DELETE")
// search
apiRouter.HandleFunc("/files", search.GetFileSuggestions).Methods("GET")
// git
apiRouter.HandleFunc("/commit-graph", gitclient.CommitGraphHandler).Methods("GET")
apiRouter.HandleFunc("/uncommitted-files", gitclient.GetUncommittedFilesHandler).Methods("GET")
apiRouter.HandleFunc("/commit-and-maybe-push", gitclient.CommitAndMaybePushHandler).Methods("POST")
apiRouter.HandleFunc("/current-branch", gitclient.BranchHandler).Methods("GET")
// kernelspecs
apiRouter.HandleFunc("/kernelspecs", kernelspec.KernelspecAPIHandler).Methods("GET")
apiRouter.HandleFunc("/kernelspecs/{kernelName}", kernelspec.SingleKernelspecAPIHandler).Methods("GET")
apiRouter.HandleFunc("/kernelspecs/{kernel}/{resource}", kernelspec.ServeKernelResource).Methods("GET")
// kernels
apiRouter.HandleFunc("/kernels", kernel.KernelListAPIHandler).Methods("GET")
apiRouter.HandleFunc("/kernels/{kernelId}", kernel.KernelReadAPIHandler).Methods("GET")
apiRouter.HandleFunc("/api/kernels/{kernel_id}", kernel.KernelDeleteAPIHandler).Methods("DELETE")
// sessions
apiRouter.HandleFunc("/sessions", session.SessionApiHandler).Methods("GET")
apiRouter.HandleFunc("/sessions", session.SessionCreateApiHandler).Methods("POST")
//web sockets
apiRouter.HandleFunc("/kernels/{kernelId}/channels", websocket.HandleWebSocket)
apiRouter.HandleFunc("/terminals/{terminalId}", websocket.HandleTerminalWebSocket)
//cors optionsGoes Below
corsOpts := cors.New(cors.Options{
AllowedOrigins: []string{"*"}, //you service is available and allowed for this base url
AllowedMethods: []string{
http.MethodGet, //http methods for your app
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
http.MethodOptions,
http.MethodHead,
},
AllowedHeaders: []string{
"*", //or you can your header key values which you are using in your application
},
})
router.PathPrefix("/").Handler(getSpaHandler())
// Channel for graceful shutdown
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
fmt.Println(`
███████╗ █████╗ ███████╗██████╗ ███████╗██████╗
╚══███╔╝██╔══██╗██╔════╝██╔══██╗██╔════╝██╔══██╗
███╔╝ ███████║███████╗██████╔╝█████╗ ██████╔╝
███╔╝ ██╔══██║╚════██║██╔═══╝ ██╔══╝ ██╔══██╗
███████╗██║ ██║███████║██║ ███████╗██║ ██║
╚══════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚══════╝╚═╝ ╚═╝
`)
glog.Println("Zasper Server started! Listening on port", *port)
url := "http://localhost" + *port
glog.Printf("Visit Zasper webapp on %s", url)
go func() {
if err := http.ListenAndServe(*port, corsOpts.Handler(router)); err != nil && err != http.ErrServerClosed {
fmt.Printf("ListenAndServe(): %s\n", err)
}
}()
<-stop
fmt.Println("Shutting down server...")
// Cleanup function
cleanup()
// Shutdown the server gracefully
_, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
fmt.Println("Server exiting")
}
// cleanup performs cleanup operations
func cleanup() {
fmt.Println("Performing cleanup...")
kernel.Cleanup()
}