surrealpatch/web/web.go

81 lines
1.9 KiB
Go
Raw Normal View History

2016-04-03 21:48:57 +00:00
// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//,
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package web
import (
"github.com/abcum/fibre"
"github.com/abcum/fibre/mw"
"github.com/abcum/surreal/cnf"
2016-04-10 15:59:01 +00:00
"github.com/abcum/surreal/log"
2016-04-03 21:48:57 +00:00
)
// Setup sets up the server for remote connections
func Setup(opts *cnf.Options) (err error) {
2016-06-18 13:42:06 +00:00
log.WithPrefix("web").Infof("Starting web server on %s", opts.Conn.Web)
2016-04-03 21:48:57 +00:00
2016-06-18 13:42:06 +00:00
s := fibre.Server(opts)
2016-04-03 21:48:57 +00:00
routes(s)
2016-07-06 18:12:14 +00:00
s.SetWait("15s")
2016-06-18 13:42:06 +00:00
s.SetName("web")
2016-04-03 21:48:57 +00:00
s.SetHTTPErrorHandler(errors)
2016-04-10 15:59:01 +00:00
s.Logger().SetLogger(log.Instance())
2016-04-03 21:48:57 +00:00
// Setup middleware
s.Use(conf()) // Setup conf
s.Use(auth()) // Setup auth
2016-04-03 21:48:57 +00:00
s.Use(mw.Logs()) // Log requests
s.Use(mw.Fail()) // Catch panics
s.Use(mw.Gzip()) // Gzip responses
s.Use(mw.Uniq()) // Add uniq headers
s.Use(mw.Cors()) // Add cors headers
// Check body size
s.Use(mw.Size(&mw.SizeOpts{
2016-09-14 09:19:08 +00:00
AllowedLength: 1 << 22,
2016-04-03 21:48:57 +00:00
}))
// Check body type
s.Use(mw.Type(&mw.TypeOpts{
2016-10-14 21:54:54 +00:00
AllowedContent: map[string]bool{
"application/json": true,
"application/cbor": true,
"application/msgpack": true,
2016-04-03 21:48:57 +00:00
},
}))
// Run the server
2016-06-18 13:42:06 +00:00
if len(opts.Cert.Crt) == 0 || len(opts.Cert.Key) == 0 {
s.Run(opts.Conn.Web)
2016-04-13 14:40:19 +00:00
}
2016-06-18 13:42:06 +00:00
if len(opts.Cert.Crt) != 0 && len(opts.Cert.Key) != 0 {
s.Run(opts.Conn.Web, opts.Cert.Crt, opts.Cert.Key)
2016-04-13 14:40:19 +00:00
}
2016-04-03 21:48:57 +00:00
return nil
}
// Exit tears down the server gracefully
func Exit() {
2016-06-18 13:42:06 +00:00
log.WithPrefix("web").Infof("Gracefully shutting down %s protocol", "web")
2016-04-03 21:48:57 +00:00
}