Files
mattermost/api/server.go

91 lines
2.3 KiB
Go
Raw Normal View History

// Copyright (c) 2015 Mattermost, Inc. All Rights Reserved.
2015-06-14 23:53:32 -08:00
// See License.txt for license information.
package api
import (
2016-01-11 09:12:51 -06:00
l4g "github.com/alecthomas/log4go"
2015-06-14 23:53:32 -08:00
"github.com/braintree/manners"
"github.com/gorilla/mux"
"github.com/mattermost/platform/store"
"github.com/mattermost/platform/utils"
2015-11-23 15:51:43 -08:00
"gopkg.in/throttled/throttled.v1"
throttledStore "gopkg.in/throttled/throttled.v1/store"
2015-06-14 23:53:32 -08:00
"net/http"
2015-07-29 01:26:10 -08:00
"strings"
2015-06-14 23:53:32 -08:00
"time"
)
type Server struct {
Store store.Store
Router *mux.Router
}
var Srv *Server
func NewServer() {
l4g.Info(utils.T("api.server.new_server.init.info"))
2015-06-14 23:53:32 -08:00
Srv = &Server{}
Srv.Store = store.NewSqlStore()
Srv.Router = mux.NewRouter()
Srv.Router.NotFoundHandler = http.HandlerFunc(Handle404)
}
func StartServer() {
l4g.Info(utils.T("api.server.start_server.starting.info"))
l4g.Info(utils.T("api.server.start_server.listening.info"), utils.Cfg.ServiceSettings.ListenAddress)
2015-07-29 01:26:10 -08:00
var handler http.Handler = Srv.Router
if utils.Cfg.RateLimitSettings.EnableRateLimiter {
l4g.Info(utils.T("api.server.start_server.rate.info"))
2015-07-29 01:26:10 -08:00
vary := throttled.VaryBy{}
if utils.Cfg.RateLimitSettings.VaryByRemoteAddr {
vary.RemoteAddr = true
}
if len(utils.Cfg.RateLimitSettings.VaryByHeader) > 0 {
vary.Headers = strings.Fields(utils.Cfg.RateLimitSettings.VaryByHeader)
if utils.Cfg.RateLimitSettings.VaryByRemoteAddr {
l4g.Warn(utils.T("api.server.start_server.rate.warn"))
2015-07-29 01:26:10 -08:00
vary.RemoteAddr = false
}
}
th := throttled.RateLimit(throttled.PerSec(utils.Cfg.RateLimitSettings.PerSec), &vary, throttledStore.NewMemStore(utils.Cfg.RateLimitSettings.MemoryStoreSize))
th.DeniedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
l4g.Error("%v: code=429 ip=%v", r.URL.Path, GetIpAddress(r))
throttled.DefaultDeniedHandler.ServeHTTP(w, r)
})
handler = th.Throttle(Srv.Router)
}
2015-06-14 23:53:32 -08:00
go func() {
2015-11-23 15:51:43 -08:00
err := manners.ListenAndServe(utils.Cfg.ServiceSettings.ListenAddress, handler)
2015-06-14 23:53:32 -08:00
if err != nil {
l4g.Critical(utils.T("api.server.start_server.starting.critical"), err)
2015-06-14 23:53:32 -08:00
time.Sleep(time.Second)
panic(utils.T("api.server.start_server.starting.panic") + err.Error())
2015-06-14 23:53:32 -08:00
}
}()
}
func StopServer() {
l4g.Info(utils.T("api.server.stop_server.stopping.info"))
2015-06-14 23:53:32 -08:00
2015-11-23 15:51:43 -08:00
manners.Close()
2015-06-14 23:53:32 -08:00
Srv.Store.Close()
hub.Stop()
2015-06-14 23:53:32 -08:00
l4g.Info(utils.T("api.server.stop_server.stopped.info"))
2015-06-14 23:53:32 -08:00
}