-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibserver.go
1464 lines (1290 loc) · 38.7 KB
/
libserver.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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package frizzante
import (
"bytes"
"context"
"database/sql"
"embed"
"encoding/json"
"errors"
"fmt"
"github.com/gorilla/websocket"
uuid "github.com/nu7hatch/gouuid"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"strings"
"sync"
"time"
)
type Server struct {
hostName string
port int
securePort int
multipartFormMaxMemory int64
server *http.Server
database *sql.DB
mux *http.ServeMux
sessions map[string]*net.Conn
readTimeout time.Duration
writeTimeout time.Duration
maxHeaderBytes int
logger *log.Logger
certificate string
certificateKey string
errorHandler func(error)
temporaryDirectory string
embeddedFileSystem embed.FS
webSocketUpgrader *websocket.Upgrader
sessionOperator func(string) (
get func(key string, defaultValue any) (value any),
set func(key string, value any),
unset func(key string),
validate func() (valid bool),
destroy func(),
)
}
type sessionStore struct {
createdAt time.Time
lastActivityAt time.Time
data map[string]any
}
// ServerCreate creates a server.
func ServerCreate() *Server {
var memory = map[string]sessionStore{}
return &Server{
hostName: "127.0.0.1",
port: 8081,
securePort: 8383,
server: nil,
mux: http.NewServeMux(),
sessions: map[string]*net.Conn{},
readTimeout: 10 * time.Second,
writeTimeout: 10 * time.Second,
maxHeaderBytes: 3 * MB,
logger: log.Default(),
certificate: "",
certificateKey: "",
errorHandler: func(error) {},
temporaryDirectory: ".temp",
webSocketUpgrader: &websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
},
sessionOperator: func(id string) (
get func(key string, defaultValue any) (value any),
set func(key string, value any),
unset func(key string),
validate func() (valid bool),
destroy func(),
) {
store, exists := memory[id]
if !exists {
store = sessionStore{
data: map[string]any{},
createdAt: time.Now(),
lastActivityAt: time.Now(),
}
memory[id] = store
}
get = func(key string, defaultValue any) (value any) {
sessionItem, ok := store.data[key]
if !ok {
store.data[key] = defaultValue
value = store.data[key]
store.lastActivityAt = time.Now()
return
}
store.lastActivityAt = time.Now()
value = sessionItem
return
}
set = func(key string, value any) {
store.lastActivityAt = time.Now()
store.data[key] = value
}
unset = func(key string) {
store.lastActivityAt = time.Now()
delete(store.data, key)
}
validate = func() (valid bool) {
elapsedSeconds := time.Since(store.lastActivityAt).Minutes()
valid = elapsedSeconds < 30
return
}
destroy = func() {
delete(memory, id)
}
return
},
}
}
// ServerWithDatabase sets the server database.
func ServerWithDatabase(self *Server, database *sql.DB) {
self.database = database
}
// ServerWithWebSocketReadBufferSize sets the maximum buffer size for each incoming web socket message.
// This will not limit the size of said messages.
func ServerWithWebSocketReadBufferSize(self *Server, readBufferSize int) {
self.webSocketUpgrader.ReadBufferSize = readBufferSize
}
// ServerWithWebSocketWriteBufferSize sets the maximum buffer size for each outgoing web socket message.
// This will not limit the size of said messages.
func ServerWithWebSocketWriteBufferSize(self *Server, writeBufferSize int) {
self.webSocketUpgrader.WriteBufferSize = writeBufferSize
}
// ServerWithMultipartFormMaxMemory sets the maximum memory for multipart forms before they fall back to disk.
func ServerWithMultipartFormMaxMemory(self *Server, multipartFormMaxMemory int64) {
self.multipartFormMaxMemory = multipartFormMaxMemory
}
// ServerWithHostName sets the host name.
func ServerWithHostName(self *Server, hostName string) {
self.hostName = hostName
}
// ServerWithPort sets the port.
func ServerWithPort(self *Server, port int) {
self.port = port
}
// ServerWithSecurePort sets the secure port.
func ServerWithSecurePort(self *Server, securePort int) {
self.securePort = securePort
}
// ServerWithReadTimeout sets the read timeout.
func ServerWithReadTimeout(self *Server, readTimeout time.Duration) {
self.readTimeout = readTimeout
}
// ServerWithWriteTimeout sets the write timeout.
func ServerWithWriteTimeout(self *Server, writeTimeout time.Duration) {
self.writeTimeout = writeTimeout
}
// ServerWithMaxHeaderBytes sets the maximum allowed bytes in the header of the request.
func ServerWithMaxHeaderBytes(self *Server, maxHeaderBytes int) {
self.maxHeaderBytes = maxHeaderBytes
}
// ServerWithLogger sets the server logger.
func ServerWithLogger(self *Server, logger *log.Logger) {
self.logger = logger
}
// ServerWithCertificateAndKey sets the tls configuration.
func ServerWithCertificateAndKey(self *Server, certificate string, key string) {
self.certificate = certificate
self.certificateKey = key
}
// ServerWithTemporaryDirectory sets the temporary directory.
func ServerWithTemporaryDirectory(self *Server, temporaryDirectory string) {
self.temporaryDirectory = temporaryDirectory
}
// ServerWithEmbeddedFileSystem sets the embedded file system.
//
// The embedded file system should contain at least directory ".dist" so
// that the server can properly render and serve svelte components.
func ServerWithEmbeddedFileSystem(self *Server, embeddedFileSystem embed.FS) {
self.embeddedFileSystem = embeddedFileSystem
}
// ServerTemporaryFileSave sets a temporary file.
//
// When id is longer than 255 characters, the operation will fail silently and the server will be notified.
func ServerTemporaryFileSave(self *Server, id string, contents string) {
if len(id) > 255 {
ServerNotifyError(self, fmt.Errorf("temporary file id is too long"))
return
}
if strings.Contains(id, "../") {
ServerNotifyError(self, fmt.Errorf("invalid substring `../` detected in temporary file id `%s`", id))
return
}
if !Exists(self.temporaryDirectory) {
mkdirError := os.MkdirAll(self.temporaryDirectory, os.ModePerm)
if mkdirError != nil {
ServerNotifyError(self, mkdirError)
return
}
}
fileName := self.temporaryDirectory
if !strings.HasSuffix(fileName, "/") && !strings.HasPrefix(id, "/") {
fileName += "/"
}
fileName += id
directory := filepath.Dir(fileName)
if !Exists(directory) {
mkdirError := os.MkdirAll(directory, os.ModePerm)
if mkdirError != nil {
ServerNotifyError(self, mkdirError)
return
}
}
var file *os.File
if !ServerTemporaryFileExists(self, id) {
fileLocal, createError := os.Create(fileName)
if createError != nil {
ServerNotifyError(self, createError)
return
}
file = fileLocal
} else {
fileLocal, openError := os.Open(fileName)
if openError != nil {
ServerNotifyError(self, openError)
return
}
file = fileLocal
}
_, writeError := file.WriteString(contents)
if writeError != nil {
ServerNotifyError(self, writeError)
return
}
closeError := file.Close()
if closeError != nil {
ServerNotifyError(self, closeError)
return
}
}
// ServerTemporaryFile gets the contents o a temporary file.
func ServerTemporaryFile(self *Server, id string) string {
if strings.Contains(id, "../") {
ServerNotifyError(self, fmt.Errorf("invalid substring `../` detected in temporary file id `%s`", id))
return ""
}
fileName := self.temporaryDirectory
if !strings.HasSuffix(fileName, "/") && !strings.HasPrefix(id, "/") {
fileName += "/"
}
fileName += id
contents, err := os.ReadFile(fileName)
if err != nil {
ServerNotifyError(self, err)
return ""
}
return string(contents)
}
// ServerTemporaryFileExists checks if a temporary file Exists.
//
// When id is longer than 255 characters, the operation will fail silently and the server will be notified.
func ServerTemporaryFileExists(self *Server, id string) bool {
if len(id) > 255 {
ServerNotifyError(self, fmt.Errorf("temporary file id is too long"))
return false
}
if strings.Contains(id, "../") {
return false
}
fileName := self.temporaryDirectory
if !strings.HasSuffix(fileName, "/") && !strings.HasPrefix(id, "/") {
fileName += "/"
}
fileName += id
return Exists(fileName)
}
// ServerTemporaryDirectoryClear clears the temporary directory.
func ServerTemporaryDirectoryClear(self *Server) {
err := os.RemoveAll(self.temporaryDirectory)
if err != nil {
ServerNotifyError(self, err)
}
}
// ReceiveCookie reads the contents of a cookie from the message and returns the value.
//
// Compatible with web sockets.
func ReceiveCookie(self *Request, key string) string {
cookie, cookieError := self.HttpRequest.Cookie(key)
if cookieError != nil {
ServerNotifyError(self.server, cookieError)
return ""
}
value, unescapeError := url.QueryUnescape(cookie.Value)
if unescapeError != nil {
return ""
}
return value
}
// ReceiveMessage reads the contents of the message and returns the value.
//
// Compatible with web sockets.
func ReceiveMessage(self *Request) string {
if self.webSocket != nil {
_, readBytes, readError := self.webSocket.ReadMessage()
if readError != nil {
ServerNotifyError(self.server, readError)
return ""
}
return string(readBytes)
}
readBytes, readAllError := io.ReadAll(self.HttpRequest.Body)
if readAllError != nil {
ServerNotifyError(self.server, readAllError)
return ""
}
return string(readBytes)
}
// ReceiveJson reads the message as json and stores the result into value.
//
// Compatible with web sockets.
func ReceiveJson[T any](self *Request, value *T) {
if self.webSocket != nil {
jsonError := self.webSocket.ReadJSON(value)
if jsonError != nil {
ServerNotifyError(self.server, jsonError)
return
}
return
}
readBytes, readAllError := io.ReadAll(self.HttpRequest.Body)
if readAllError != nil {
ServerNotifyError(self.server, readAllError)
return
}
unmarshalError := json.Unmarshal(readBytes, &value)
if unmarshalError != nil {
ServerNotifyError(self.server, unmarshalError)
}
}
// ReceiveForm reads the message as a form and returns the value.
func ReceiveForm(self *Request) *url.Values {
if self.webSocket != nil {
ServerNotifyError(self.server, errors.New("web socket connections cannot receive form payloads"))
return nil
}
parseMultipartFormError := self.HttpRequest.ParseMultipartForm(self.server.multipartFormMaxMemory)
if parseMultipartFormError != nil {
if !errors.Is(parseMultipartFormError, http.ErrNotMultipart) {
ServerNotifyError(self.server, parseMultipartFormError)
}
parseFormError := self.HttpRequest.ParseForm()
if parseFormError != nil {
ServerNotifyError(self.server, parseFormError)
}
}
return &self.HttpRequest.Form
}
// ReceiveQuery reads a query field and returns the value.
//
// Compatible with web sockets.
func ReceiveQuery(self *Request, name string) string {
return self.HttpRequest.URL.Query().Get(name)
}
// ReceivePath reads a path fields and returns the value.
//
// Compatible with web sockets.
func ReceivePath(self *Request, name string) string {
return self.HttpRequest.PathValue(name)
}
// ReceiveHeader reads a header field and returns the value.
//
// Compatible with web sockets.
func ReceiveHeader(self *Request, key string) string {
return self.HttpRequest.Header.Get(key)
}
// ReceiveContentType reads the Content-Type header field and returns the value.
//
// Compatible with web sockets.
func ReceiveContentType(self *Request) string {
return self.HttpRequest.Header.Get("Content-Type")
}
// ServerStart starts the server.
//
// If the server fails to start, ServerStart panics.
func ServerStart(self *Server) {
self.server = &http.Server{
Handler: self.mux,
ReadTimeout: self.readTimeout,
WriteTimeout: self.writeTimeout,
MaxHeaderBytes: self.maxHeaderBytes,
ErrorLog: self.logger,
}
if !entryCreated {
ServerWithApi(self, "GET /",
func(server *Server, request *Request, response *Response) {
SendStatus(response, 404)
},
)
}
var waiter sync.WaitGroup
waiter.Add(2)
go func() {
address := fmt.Sprintf("%s:%d", self.hostName, self.port)
self.logger.Printf("listening for requests at http://%s", address)
err := http.ListenAndServe(address, self.mux)
if err != nil {
if errors.Is(err, http.ErrServerClosed) {
self.logger.Println("shutting down server")
return
}
panic(err.Error())
}
}()
go func() {
secureAddress := fmt.Sprintf("%s:%d", self.hostName, self.securePort)
if "" != self.certificate && "" != self.certificateKey {
self.logger.Printf("listening for requests at https://%s", secureAddress)
err := http.ListenAndServeTLS(secureAddress, self.certificate, self.certificateKey, self.mux)
if err != nil {
if errors.Is(err, http.ErrServerClosed) {
self.logger.Println("shutting down server")
return
}
panic(err.Error())
}
}
}()
waiter.Wait()
}
// ServerStop attempts to stop the server.
//
// If the shutdown attempt fails, ServerStop panics.
func ServerStop(self *Server) {
err := self.server.Shutdown(context.Background())
if err != nil {
panic(err.Error())
}
}
var pathParametersPattern = regexp.MustCompile(`{([^{}]+)}`)
type Route struct {
server *Server
isPage bool
pageId string
callback func(server *Server, request *Request, response *Response)
mount func(pattern string)
}
// RouteCreate creates a route configuration from a callback function.
func RouteCreate(
callback func(
server *Server,
request *Request,
response *Response,
),
) *Route {
return &Route{
isPage: false,
pageId: "",
callback: callback,
mount: func(pattern string) {},
}
}
// RouteCreateWithPage creates a route configuration from a callback function, just like RouteCreate.
//
// Unlike RouteCreate, RouteCreateWithPage also creates a Page, which is used to automatically
// to serve a svelte page after invoking callback.
//
// Generally speaking, you should never manually invoke SendEcho or similar functions.
//
// However, it is safe to invoke receive functions, like ReceiveHeader, ReceiveCookie, etc.
func RouteCreateWithPage(
pageId string,
callback func(
server *Server,
request *Request,
response *Response,
page *Page,
),
) *Route {
var pattern string
if strings.HasSuffix(pageId, ".svelte") {
pageId = strings.TrimSuffix(pageId, ".svelte")
}
return &Route{
isPage: true,
pageId: pageId,
callback: func(
server *Server,
request *Request,
response *Response,
) {
page := &Page{
renderMode: RenderModeFull,
data: map[string]interface{}{},
pageId: pageId,
embeddedFileSystem: server.embeddedFileSystem,
}
callback(server, request, response, page)
if nil == page {
ServerNotifyError(server, fmt.Errorf("svelte page handler `%s` returned a nil page", pattern))
return
}
if nil == page.data {
page.data = map[string]any{}
}
parseMultipartFormError := request.HttpRequest.ParseMultipartForm(1024)
if parseMultipartFormError != nil {
if !errors.Is(parseMultipartFormError, http.ErrNotMultipart) {
ServerNotifyError(server, parseMultipartFormError)
}
parseFormError := request.HttpRequest.ParseForm()
if parseFormError != nil {
ServerNotifyError(server, parseFormError)
}
}
pathEntry := map[string]string{}
for _, name := range pathParametersPattern.FindAllStringSubmatch(pattern, -1) {
if len(name) < 1 {
continue
}
pathEntry[name[1]] = request.HttpRequest.PathValue(name[1])
}
page.data["path"] = pathEntry
page.data["query"] = request.HttpRequest.URL.Query()
page.data["form"] = request.HttpRequest.Form
if VerifyAccept(request, "application/json") {
data, marshalError := json.Marshal(page.data)
if marshalError != nil {
ServerNotifyError(server, marshalError)
return
}
SendHeader(response, "Content-Type", "application/json")
SendEcho(response, string(data))
return
}
SendPage(response, page)
},
mount: func(patternLocal string) {
pattern = patternLocal
patternParts := strings.Split(patternLocal, " ")
patternCounter := len(patternParts)
if patternCounter > 1 {
pagesToPaths[pageId] = path.Join(patternParts[1:]...)
}
},
}
}
// RouteCreateWithPageAndHeadless creates a headless route configuration from a callback function, just like RouteCreate.
//
// Unlike RouteCreate, RouteCreateWithPageAndHeadless also creates a Page, which is used to automatically
// to serve a svelte page after invoking callback.
//
// Generally speaking, you should never manually invoke SendEcho or similar functions.
//
// However, it is safe to invoke receive functions, like ReceiveHeader, ReceiveCookie, etc.
//
// Rendering a headless page means it's automatically rendering in server mode,
// it omits the head tag, the body tag and all css.
func RouteCreateWithPageAndHeadless(
pageId string,
callback func(
server *Server,
request *Request,
response *Response,
page *Page,
),
) *Route {
return RouteCreateWithPage(pageId,
func(server *Server, request *Request, response *Response, page *Page) {
page.headless = true
callback(server, request, response, page)
},
)
}
var entryCreated = false
// ServerWithRoute registers a callback for the given pattern.
//
// If the given pattern conflicts with one that is already registered, ServerWithRoute panics.
func ServerWithRoute(
self *Server,
pattern string,
route *Route,
) {
patternParts := strings.Split(pattern, " ")
patternCounter := len(patternParts)
isEntry := patternCounter > 1 && strings.HasPrefix(strings.TrimPrefix(filepath.Join(patternParts[1:]...), " "), "/")
if isEntry && !entryCreated {
entryCreated = true
}
if route.mount != nil {
route.mount(pattern)
}
self.mux.HandleFunc(pattern, func(writer http.ResponseWriter, httpRequest *http.Request) {
request := Request{
server: self,
HttpRequest: httpRequest,
}
httpHeader := writer.Header()
response := Response{
server: self,
writer: &writer,
lockedStatusAndHeader: false,
statusCode: 200,
header: &httpHeader,
}
request.response = &response
response.request = &request
if isEntry {
SendEmbeddedFileOrElse(&response, func() {
SendFileOrElse(&response, func() {
if route.callback != nil {
route.callback(self, &request, &response)
}
})
})
} else if route.callback != nil {
route.callback(self, &request, &response)
}
})
}
type Request struct {
server *Server
response *Response
HttpRequest *http.Request
webSocket *websocket.Conn
}
type Response struct {
server *Server
request *Request
writer *http.ResponseWriter
lockedStatusAndHeader bool
statusCode int
header *http.Header
webSocket *websocket.Conn
}
// ServerWithErrorReceiver sets the error receiver.
func ServerWithErrorReceiver(self *Server, callback func(err error)) {
self.errorHandler = callback
}
// ServerNotifyError notifies the server of an error.
func ServerNotifyError(self *Server, err error) {
self.errorHandler(err)
}
// SendRedirect redirects the request.
func SendRedirect(self *Response, location string, statusCode int) {
SendStatus(self, statusCode)
SendHeader(self, "Location", location)
SendEcho(self, "")
}
// SendRedirectToSecure tries to redirect the request to the https server.
//
// When the request is already secure, SendRedirectToSecure returns false.
func SendRedirectToSecure(self *Response, statusCode int) bool {
request := self.request
if "" == request.server.certificate || "" == request.server.certificateKey || request.HttpRequest.TLS != nil {
return false
}
insecureSuffix := fmt.Sprintf(":%d", request.server.port)
secureSuffix := fmt.Sprintf(":%d", request.server.securePort)
secureHost := strings.Replace(request.HttpRequest.Host, insecureSuffix, secureSuffix, 1)
secureLocation := fmt.Sprintf("https://%s%s", secureHost, request.HttpRequest.RequestURI)
SendRedirect(self, secureLocation, statusCode)
return true
}
// SendStatus sets the status code.
//
// This will lock the status, which makes it
// so that the next time you invoke this
// function it will fail with an error.
//
// You can retrieve the error using ServerWithErrorReceiver.
func SendStatus(self *Response, code int) {
if self.lockedStatusAndHeader {
ServerNotifyError(self.server, errors.New("status is locked"))
return
}
self.statusCode = code
}
// SendHeader sets a header field.
//
// If the status has not been sent already, a default "200 OK" status will be sent immediately.
//
// This means the status will become locked and further attempts to send the status will fail with an error.
//
// You can retrieve the error using ServerWithErrorReceiver
func SendHeader(self *Response, key string, value string) {
if self.lockedStatusAndHeader {
ServerNotifyError(self.server, errors.New("headers locked"))
return
}
self.header.Set(key, value)
}
// SendContentType sets the Content-Type header field.
func SendContentType(self *Response, contentType string) {
SendHeader(self, "Content-Type", contentType)
}
// SendCookie sends a cookies to the client.
func SendCookie(self *Response, key string, value string) {
SendHeader(self, "set-Cookie", fmt.Sprintf("%s=%s", url.QueryEscape(key), url.QueryEscape(value)))
}
// SendContent sends binary safe content.
//
// If the status code or the header have not been sent already, a default status of "200 OK" will be sent immediately along with whatever headers you've previously defined.
//
// The status code and the header will become locked and further attempts to send either of them will fail with an error.
//
// You can retrieve the error using ServerWithErrorReceiver.
//
// Compatible with web sockets.
func SendContent(self *Response, content []byte) {
if !self.lockedStatusAndHeader {
(*self.writer).WriteHeader(self.statusCode)
self.lockedStatusAndHeader = true
}
if self.webSocket != nil {
writeError := self.webSocket.WriteMessage(websocket.TextMessage, content)
if writeError != nil {
ServerNotifyError(self.server, writeError)
}
return
}
_, err := (*self.writer).Write(content)
if err != nil {
ServerNotifyError(self.server, err)
return
}
}
// SendEcho sends utf-8 safe content.
//
// If the status code or the header have not been sent already, a default status of "200 OK" will be sent immediately along with whatever headers you've previously defined.
//
// The status code and the header will become locked and further attempts to send either of them will fail with an error.
//
// You can retrieve the error using ServerWithErrorReceiver.
//
// Compatible with web sockets.
func SendEcho(self *Response, content string) {
SendContent(self, []byte(content))
}
// SendJson sends json content.
//
// If the status code or the header have not been sent already, a default status of "200 OK" will be sent immediately along with whatever headers you've previously defined.
//
// The status code and the header will become locked and further attempts to send either of them will fail with an error.
//
// You can retrieve the error using ServerWithErrorReceiver.
//
// Compatible with web sockets.
func SendJson(self *Response, payload any) {
content, marshalError := json.Marshal(payload)
if marshalError != nil {
ServerNotifyError(self.server, marshalError)
}
if nil == self.webSocket {
contentType := self.header.Get("Content-Type")
if "" == contentType {
self.header.Set("Content-Type", "application/json")
}
}
SendContent(self, content)
}
// VerifyContentType checks if the incoming request has any of the given content-types.
func VerifyContentType(self *Request, contentTypes ...string) bool {
requestedMime := self.HttpRequest.Header.Get("Content-Type")
for _, acceptedMime := range contentTypes {
if acceptedMime == "*" || strings.HasPrefix(requestedMime, acceptedMime) {
return true
}
}
return false
}
// VerifyAccept checks if the incoming request accepts any of the given content-types.
func VerifyAccept(self *Request, contentTypes ...string) bool {
requestedAcceptMime := self.HttpRequest.Header.Get("Accept")
for _, acceptedMime := range contentTypes {
if acceptedMime == "*" || strings.Contains(requestedAcceptMime, acceptedMime) {
return true
}
}
return false
}
// SendEmbeddedFileOrIndexOrElse sends the embedded file requested by the client,
// or the closest index.html embedded file, or else falls back.
func SendEmbeddedFileOrIndexOrElse(self *Response, orElse func()) {
request := self.request
fileName := filepath.Join(".dist", "client", request.HttpRequest.RequestURI)
if !EmbeddedExists(request.server.embeddedFileSystem, fileName) {
orElse()
return
}
if EmbeddedIsDirectory(request.server.embeddedFileSystem, fileName) {
fileName = filepath.Join(fileName, "index.html")
if !IsFile(fileName) {
orElse()
return
}
}
reader, info, readerError := createReaderFromEmbeddedFileName(&request.server.embeddedFileSystem, fileName)
if readerError != nil {
ServerNotifyError(self.server, readerError)
return
}
SendHeader(self, "Content-Type", Mime(fileName))
SendHeader(self, "Content-Length", fmt.Sprintf("%d", (*info).Size()))
http.ServeContent(*self.writer, request.HttpRequest, fileName, (*info).ModTime(), reader)
}
// SendEmbeddedFileOrElse sends the embedded file requested by the client,
// or the closest index.html embedded file, or else falls back.
func SendEmbeddedFileOrElse(self *Response, orElse func()) {
request := self.request
fileName := filepath.Join(".dist", "client", request.HttpRequest.RequestURI)
fileName = strings.Split(fileName, "?")[0]
fileName = strings.Split(fileName, "&")[0]
if !EmbeddedExists(request.server.embeddedFileSystem, fileName) ||
EmbeddedIsDirectory(request.server.embeddedFileSystem, fileName) {
orElse()
return
}
reader, info, readerError := createReaderFromEmbeddedFileName(&request.server.embeddedFileSystem, fileName)
if readerError != nil {
ServerNotifyError(self.server, readerError)
return
}
SendHeader(self, "Content-Type", Mime(fileName))
SendHeader(self, "Content-Length", fmt.Sprintf("%d", (*info).Size()))
http.ServeContent(*self.writer, request.HttpRequest, fileName, (*info).ModTime(), reader)
}
// SendFileOrIndexOrElse sends the file requested by the client,
// or the closest index.html file, or else falls back.
func SendFileOrIndexOrElse(self *Response, orElse func()) {
request := self.request
fileName := filepath.Join(".dist", "client", request.HttpRequest.RequestURI)
if !Exists(fileName) {
orElse()
return
}
if IsDirectory(fileName) {
fileName = filepath.Join(fileName, "index.html")
if !IsFile(fileName) {
orElse()
return
}
}
reader, info, readerError := createReaderFromFileName(fileName)
if readerError != nil {
ServerNotifyError(self.server, readerError)
return
}
SendHeader(self, "Content-Type", Mime(fileName))
SendHeader(self, "Content-Length", fmt.Sprintf("%d", (*info).Size()))
http.ServeContent(*self.writer, request.HttpRequest, fileName, (*info).ModTime(), reader)
}
// SendFileOrElse sends the file requested by the client, or else falls back.
func SendFileOrElse(self *Response, orElse func()) {
request := self.request
fileName := filepath.Join(".dist", "client", request.HttpRequest.RequestURI)
if !Exists(fileName) || IsDirectory(fileName) {
orElse()
return
}
reader, info, readerError := createReaderFromFileName(fileName)
if readerError != nil {
ServerNotifyError(self.server, readerError)
return
}
SendHeader(self, "Content-Type", Mime(fileName))
SendHeader(self, "Content-Length", fmt.Sprintf("%d", (*info).Size()))