forked from cernodile/reEgg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
165 lines (147 loc) · 4.14 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
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
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"io"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"time"
)
type wrappedHandleFunc func(w http.ResponseWriter, req *http.Request) error
//var debugOneThingAtATime sync.Mutex
func wrapHandleFunc(whf wrappedHandleFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
//debugOneThingAtATime.Lock()
//defer debugOneThingAtATime.Unlock()
if err := whf(w, req); err != nil {
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, err.Error())
}
// is it a good idea to do this here?
// that way no one can forget to do it
req.Body.Close()
}
}
// removed on release due to logspam
// but useful for devving to not miss anything
func printUnhandled(w http.ResponseWriter, req *http.Request) error {
/*
dump, err := httputil.DumpRequest(req, true)
if err != nil {
log.Printf("failed to dump request: %s", err)
return errors.New("bad request")
}
log.Printf("Unhandled Request:\n%s\nEND Unhandled Request", strings.TrimSpace(string(dump)))
*/
return errors.New("Whatever you requested is unhandled right now")
}
var (
userdir = flag.String("datadir", "data", "where the userdata is stored")
)
func main() {
log.SetFlags(log.Lshortfile)
flag.Parse()
config, workingpath := loadConfig(*userdir)
log.Printf("config: %q", config)
egg := newEggstore(config.Motd, workingpath)
mux := http.NewServeMux()
// Handle /ei/ posts
mux.HandleFunc("POST /ei/{subpath...}", wrapHandleFunc(egg.handlepath_ei))
mux.HandleFunc("POST /ei", wrapHandleFunc(egg.handlepath_ei)) //is this a thing? we certainly need a handler or it disappears into the void
// Analytics
mux.HandleFunc("POST /ei_data/{subpath...}", wrapHandleFunc(egg.handlepath_eidata))
// Redirect a pure call to "/" to the Landing Page
mux.HandleFunc("GET /{$}", redirect)
// Landing Pages
mux.HandleFunc("GET /info", egg.index(config.AdminContact))
mux.HandleFunc("GET /favicon.ico", getico)
mux.HandleFunc("GET /privacy", redirect) // the in app privacy button takes us here, forward it
// Catch-all the rest
mux.HandleFunc("/", wrapHandleFunc(printUnhandled))
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, os.Kill)
srv := &http.Server{Handler: mux, Addr: ":80"}
log.Printf("Starting HTTP server: %v", srv.Addr)
go func() {
err := srv.ListenAndServe()
log.Print(err)
// if the server crashed we exit
stop <- os.Kill
}()
quitperiodicalrunner := make(chan struct{})
go func() {
// we save our state every minute to the files
interval := time.NewTicker(1 * time.Minute)
defer interval.Stop()
for {
select {
case <-interval.C:
egg.SaveData()
case <-quitperiodicalrunner:
return
}
}
}()
<-stop
quitperiodicalrunner <- struct{}{}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
srv.Shutdown(ctx)
egg.Shutdown()
}
type Config struct {
Motd string
AdminContact string
}
func loadConfig(userdir string) (Config, string) {
fullpath, err := filepath.Abs(userdir)
if err != nil {
log.Panic(err)
}
_, err = os.Stat(fullpath)
if err != nil {
if os.IsNotExist(err) {
log.Panicf("directory doesnt exist: %s", fullpath)
}
// other error
log.Panic(err)
}
joined := filepath.Join(fullpath, "settings.json")
serversettingsfile, err := os.Open(joined)
if err != nil {
if os.IsNotExist(err) {
log.Printf("Making a new config file for you in %s", fullpath)
serversettingsfile, err = os.Create(joined)
if err != nil {
log.Panic(err)
}
emptyconfig := Config{
Motd: "WELCOME TO reEgg-go!!\nA custom server!!\ngithub.com/BieHDC/reEgg",
AdminContact: "https://github.com/BieHDC/reEgg",
}
encoder := json.NewEncoder(serversettingsfile)
encoder.SetIndent("", "\t")
err = encoder.Encode(&emptyconfig)
if err != nil {
log.Panic(err)
}
serversettingsfile.Sync()
serversettingsfile.Seek(0, io.SeekStart)
} else {
log.Panic(err)
}
}
decoder := json.NewDecoder(serversettingsfile)
config := Config{}
err = decoder.Decode(&config)
if err != nil {
log.Panic(err)
}
serversettingsfile.Close()
return config, fullpath
}