mirror of
https://github.com/m1k1o/neko.git
synced 2024-07-24 14:40:50 +12:00
add cors.
This commit is contained in:
@ -1,6 +1,8 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"m1k1o/neko/internal/utils"
|
||||
"net/http"
|
||||
"path"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
@ -13,6 +15,7 @@ type Server struct {
|
||||
Bind string
|
||||
Static string
|
||||
PathPrefix string
|
||||
CORS []string
|
||||
}
|
||||
|
||||
func (Server) Init(cmd *cobra.Command) error {
|
||||
@ -41,6 +44,11 @@ func (Server) Init(cmd *cobra.Command) error {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd.PersistentFlags().StringSlice("cors", []string{"*"}, "list of allowed origins for CORS")
|
||||
if err := viper.BindPFlag("cors", cmd.PersistentFlags().Lookup("cors")); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -50,4 +58,15 @@ func (s *Server) Set() {
|
||||
s.Bind = viper.GetString("bind")
|
||||
s.Static = viper.GetString("static")
|
||||
s.PathPrefix = path.Join("/", path.Clean(viper.GetString("path_prefix")))
|
||||
|
||||
s.CORS = viper.GetStringSlice("cors")
|
||||
in, _ := utils.ArrayIn("*", s.CORS)
|
||||
if len(s.CORS) == 0 || in {
|
||||
s.CORS = []string{"*"}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) AllowOrigin(r *http.Request, origin string) bool {
|
||||
in, _ := utils.ArrayIn(origin, s.CORS)
|
||||
return in || s.CORS[0] == "*"
|
||||
}
|
||||
|
@ -13,6 +13,7 @@ import (
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/go-chi/chi/middleware"
|
||||
"github.com/go-chi/cors"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
@ -38,6 +39,15 @@ func New(conf *config.Server, webSocketHandler types.WebSocketHandler, desktop t
|
||||
router.Use(middleware.Recoverer) // Recover from panics without crashing server
|
||||
router.Use(middleware.Compress(5, "application/octet-stream"))
|
||||
|
||||
router.Use(cors.Handler(cors.Options{
|
||||
AllowOriginFunc: conf.AllowOrigin,
|
||||
AllowedMethods: []string{"GET", "POST", "DELETE", "OPTIONS"},
|
||||
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
|
||||
ExposedHeaders: []string{"Link"},
|
||||
AllowCredentials: true,
|
||||
MaxAge: 300, // Maximum value not ignored by any of major browsers
|
||||
}))
|
||||
|
||||
if conf.PathPrefix != "/" {
|
||||
router.Use(func(h http.Handler) http.Handler {
|
||||
return http.StripPrefix(conf.PathPrefix, h)
|
||||
|
Reference in New Issue
Block a user