memos/server/server.go

80 lines
1.7 KiB
Go
Raw Normal View History

2022-02-03 15:32:03 +08:00
package server
import (
"fmt"
2022-03-29 20:53:43 +08:00
"memos/common"
2022-05-16 07:37:23 +08:00
"memos/store"
2022-02-04 18:54:24 +08:00
"time"
2022-02-03 15:32:03 +08:00
2022-02-05 17:04:23 +08:00
"github.com/gorilla/securecookie"
2022-02-03 15:32:03 +08:00
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
type Server struct {
e *echo.Echo
2022-03-29 20:53:43 +08:00
Profile *common.Profile
2022-05-16 07:37:23 +08:00
Store *store.Store
2022-02-03 15:32:03 +08:00
}
2022-03-29 20:53:43 +08:00
func NewServer(profile *common.Profile) *Server {
2022-02-03 15:32:03 +08:00
e := echo.New()
e.Debug = true
e.HideBanner = true
e.HidePort = false
2022-02-04 18:54:24 +08:00
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: "${method} ${uri} ${status}\n",
}))
e.Use(middleware.TimeoutWithConfig(middleware.TimeoutConfig{
Skipper: middleware.DefaultSkipper,
ErrorMessage: "Request timeout",
Timeout: 30 * time.Second,
}))
2022-02-03 15:32:03 +08:00
e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
Skipper: middleware.DefaultSkipper,
Root: "web/dist",
Browse: false,
HTML5: true,
2022-02-03 15:32:03 +08:00
}))
2022-03-29 20:53:43 +08:00
// In dev mode, set the const secret key to make login session persistence.
2022-03-29 07:30:29 +08:00
secret := []byte("justmemos")
2022-05-02 09:40:25 +08:00
if profile.Mode == "prod" {
2022-03-29 07:30:29 +08:00
secret = securecookie.GenerateRandomKey(16)
}
e.Use(session.Middleware(sessions.NewCookieStore(secret)))
2022-02-03 15:32:03 +08:00
s := &Server{
2022-03-29 20:53:43 +08:00
e: e,
Profile: profile,
2022-02-03 15:32:03 +08:00
}
2022-03-29 20:53:43 +08:00
// Webhooks api skips auth checker.
2022-02-03 15:32:03 +08:00
webhookGroup := e.Group("/h")
s.registerWebhookRoutes(webhookGroup)
apiGroup := e.Group("/api")
apiGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
2022-05-16 07:37:23 +08:00
return BasicAuthMiddleware(s, next)
2022-02-03 15:32:03 +08:00
})
2022-03-29 20:53:43 +08:00
s.registerSystemRoutes(apiGroup)
2022-02-03 15:32:03 +08:00
s.registerAuthRoutes(apiGroup)
s.registerUserRoutes(apiGroup)
s.registerMemoRoutes(apiGroup)
s.registerShortcutRoutes(apiGroup)
s.registerResourceRoutes(apiGroup)
return s
}
func (server *Server) Run() error {
2022-03-29 20:53:43 +08:00
return server.e.Start(fmt.Sprintf(":%d", server.Profile.Port))
2022-02-03 15:32:03 +08:00
}