New creates a new instance of Server. Server will use the New() of the factory provided to handle each request.
(factory Factory, options *Options, redisOptions *RedisOptions)
| 40 | // New creates a new instance of Server. |
| 41 | // Server will use the New() of the factory provided to handle each request. |
| 42 | func New(factory Factory, options *Options, redisOptions *RedisOptions) (*Server, error) { |
| 43 | |
| 44 | indexData, err := Asset("static/terminal.html") |
| 45 | if err != nil { |
| 46 | panic("terminal not found") // must be in bindata |
| 47 | } |
| 48 | if options.IndexFile != "" { |
| 49 | path := homedir.Expand(options.IndexFile) |
| 50 | indexData, err = os.ReadFile(path) |
| 51 | if err != nil { |
| 52 | return nil, errors.Wrapf(err, "failed to read custom index file at `%s`", path) |
| 53 | } |
| 54 | } |
| 55 | terminalTemplate, err := template.New("index").Parse(string(indexData)) |
| 56 | if err != nil { |
| 57 | panic("index template parse failed") // must be valid |
| 58 | } |
| 59 | |
| 60 | titleTemplate, err := noesctmpl.New("title").Parse(options.TitleFormat) |
| 61 | if err != nil { |
| 62 | return nil, errors.Wrapf(err, "failed to parse window title format `%s`", options.TitleFormat) |
| 63 | } |
| 64 | |
| 65 | var originChecker func(r *http.Request) bool |
| 66 | if options.WSOrigin != "" { |
| 67 | matcher, err := regexp.Compile(options.WSOrigin) |
| 68 | if err != nil { |
| 69 | return nil, errors.Wrapf(err, "failed to compile regular expression of Websocket Origin: %s", options.WSOrigin) |
| 70 | } |
| 71 | originChecker = func(r *http.Request) bool { |
| 72 | return matcher.MatchString(r.Header.Get("Origin")) |
| 73 | } |
| 74 | } else { |
| 75 | // Don't check origin if ws-origin is not set |
| 76 | originChecker = func(r *http.Request) bool { |
| 77 | return true |
| 78 | } |
| 79 | } |
| 80 | var cache token.Cache |
| 81 | |
| 82 | if redisOptions.UseRedisTokenCache == "true" { |
| 83 | log.Println("Use redis to store token: ", redisOptions.Addr) |
| 84 | client := redis.NewClient(redisOptions.Convert()) |
| 85 | cache = token.NewRedisCache(client, "kubeoperator-webkubectl-") |
| 86 | } else { |
| 87 | cache = token.NewMemCache() |
| 88 | } |
| 89 | |
| 90 | return &Server{ |
| 91 | factory: factory, |
| 92 | options: options, |
| 93 | |
| 94 | upgrader: &websocket.Upgrader{ |
| 95 | ReadBufferSize: webtty.MaxBufferSize, |
| 96 | WriteBufferSize: webtty.MaxBufferSize, |
| 97 | Subprotocols: webtty.Protocols, |
| 98 | CheckOrigin: originChecker, |
| 99 | }, |