Skip to content

Commit

Permalink
add: cors config and rest template config
Browse files Browse the repository at this point in the history
  • Loading branch information
Lightieey committed Oct 31, 2023
1 parent 33e2fce commit 064ce1b
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/main/java/kr/co/helloplum/config/RestTemplateConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package kr.co.helloplum.config;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

@Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder();
}

@Bean
public RestTemplate restTemplate() {
return restTemplateBuilder()
.requestFactory(() -> new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()))
.setConnectTimeout(Duration.ofMillis(5000)) // connection-timeout
.setReadTimeout(Duration.ofMillis(5000)) // read-timeout
.additionalMessageConverters(new StringHttpMessageConverter(StandardCharsets.UTF_8))
.build();
}
}
34 changes: 34 additions & 0 deletions src/main/java/kr/co/helloplum/config/WebMvcConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package kr.co.helloplum.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
private final String localhost = "http://localhost:";
private final int allowedPort = 3000;
private List<String> allowedOrigins = new ArrayList<>();

// CORS
@Override
public void addCorsMappings(CorsRegistry registry) {
// 허용할 origin 목록
allowedOrigins.add(localhost + allowedPort);

registry.addMapping("/**")
.allowedOrigins(allowedOrigins.toArray(new String[allowedOrigins.size()]))
.allowedMethods(
HttpMethod.GET.name(),
HttpMethod.HEAD.name(),
HttpMethod.POST.name(),
HttpMethod.PUT.name(),
HttpMethod.PATCH.name(),
HttpMethod.DELETE.name())
.maxAge(3000); // pre-flight 리퀘스트를 캐싱
}
}

0 comments on commit 064ce1b

Please sign in to comment.