0

I tried this code but it doesn't work. I am unsure if this is even possible. I have deployed my function app as a Java .jar file and the swagger-ui/ folder is inside the .jar at the root of the archive. I don't think it can load the files and I just get back an error from the Exception block that says No file found: null

import static org.apache.commons.lang.StringUtils.isBlank;

@Slf4j
public class SwaggerHandler {

    private static final String DEFAULT_INDEX = "index.html";

    @FunctionName("swagger")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = { HttpMethod.GET },
                    authLevel = AuthorizationLevel.ANONYMOUS,
      route = "swagger-ui/{*path}") HttpRequestMessage<Optional<String>> request,
            @BindingName("path") String path
        ) throws URISyntaxException, IOException {
        try {
            if (isBlank(path)) path = DEFAULT_INDEX;
            log.info("SwaggerHandler: load " + path);
            URI resourceUri = getClass().getClassLoader()
          .getResource("swagger-ui/" + path).toURI();
            log.info("Resource URI: " + resourceUri);
            byte[] fileContent = Files.readAllBytes(Paths.get(resourceUri));
            return request.createResponseBuilder(HttpStatus.OK)
                    .header("Content-Type", getContentType(path))
                    .body(new String(fileContent, StandardCharsets.UTF_8))
                    .build();
        } catch (Exception e) {
            return request.createResponseBuilder(HttpStatus.NOT_FOUND)
                    .header("Content-Type", "text/plain")
                    .body("No file found: " + e.getMessage())
                    .build();
        }
    }

    private String getContentType(String path) {
        String extension = path.substring(path.lastIndexOf('.') + 1);
        switch (extension) {
            case "html":
                return "text/html";
            case "css":
                return "text/css";
            case "txt":
                return "text/plain";
            case "js":
                return "application/javascript";
            case "png":
                return "image/png";
            case "svg":
                return "image/svg+xml";
            case "ico":
                return "image/x-icon";
            default:
                return "application/octet-stream";
        }
    }

}

I am pretty sure I don't need any configuration related to this in my host.json, so I didn't touch that.

djangofan
  • 28,471
  • 61
  • 196
  • 289

0 Answers0