1   /*
2    * Copyright 2018 LINE Corporation
3    *
4    * LINE Corporation licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package com.linecorp.centraldogma.server.internal.admin.auth;
17  
18  import static java.util.Objects.requireNonNull;
19  
20  import com.linecorp.armeria.common.HttpRequest;
21  import com.linecorp.armeria.common.HttpResponse;
22  import com.linecorp.armeria.server.HttpService;
23  import com.linecorp.armeria.server.ServiceRequestContext;
24  import com.linecorp.armeria.server.ServiceRequestContextWrapper;
25  import com.linecorp.armeria.server.file.FileService;
26  
27  public final class OrElseDefaultHttpFileService implements HttpService {
28  
29      private final HttpService delegate;
30  
31      public OrElseDefaultHttpFileService(FileService fileService, String defaultPath) {
32          requireNonNull(fileService, "fileService");
33          requireNonNull(defaultPath, "defaultPath");
34          // Always return '/index.html' if there is no entry on the requested path, in order to route
35          // the request by 'react-router'.
36          delegate = fileService.orElse(
37                  (ctx, req) -> fileService.serve(new DefaultHtmlServiceRequestContext(ctx, defaultPath), req));
38      }
39  
40      @Override
41      public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
42          return delegate.serve(ctx, req);
43      }
44  
45      // TODO(hyangtack) Use a better HTTP file service later which serves only one file.
46      private static final class DefaultHtmlServiceRequestContext extends ServiceRequestContextWrapper {
47  
48          private final String defaultPath;
49  
50          private DefaultHtmlServiceRequestContext(ServiceRequestContext delegate, String defaultPath) {
51              super(delegate);
52              this.defaultPath = defaultPath;
53          }
54  
55          @Override
56          public String decodedMappedPath() {
57              return defaultPath;
58          }
59      }
60  }