Skip to content

Commit

Permalink
Merge pull request alibaba#596 from fudali113/fix-get-remote-ip
Browse files Browse the repository at this point in the history
  • Loading branch information
hxy1991 authored Jan 9, 2019
2 parents 5d6085f + 8ef18cb commit 8fdbf68
Show file tree
Hide file tree
Showing 5 changed files with 324 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,40 @@
*/
public class RequestUtil {

private static final String X_REAL_IP = "X-Real-IP";
private static final String X_FORWARDED_FOR = "X-Forwarded-For";
private static final String X_FORWARDED_FOR_SPLIT_SYMBOL = ",";

public static final String CLIENT_APPNAME_HEADER = "Client-AppName";

/**
* get real client ip
* <p>
* first use X-Forwarded-For header https://zh.wikipedia.org/wiki/X-Forwarded-For
* next nginx X-Real-IP
* last {@link HttpServletRequest#getRemoteAddr()}
*
* @param request {@link HttpServletRequest}
* @return
*/
public static String getRemoteIp(HttpServletRequest request) {
String nginxHeader = request.getHeader("X-Real-IP");
return (nginxHeader == null) ? request.getRemoteAddr() : nginxHeader;
String xForwardedFor = request.getHeader(X_FORWARDED_FOR);
if (!StringUtils.isBlank(xForwardedFor)) {
return xForwardedFor.split(X_FORWARDED_FOR_SPLIT_SYMBOL)[0].trim();
}
String nginxHeader = request.getHeader(X_REAL_IP);
return StringUtils.isBlank(nginxHeader) ? request.getRemoteAddr() : nginxHeader;
}

/**
* 获取 header 中的客服端应用名称
* <p>
*
* @param request {@link HttpServletRequest}
* @return 可能为 null
*/
public static String getAppName(HttpServletRequest request) {
return request.getHeader("Client-AppName");
return request.getHeader(CLIENT_APPNAME_HEADER);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.utils;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;

import javax.servlet.http.HttpServletRequest;

import static org.mockito.ArgumentMatchers.eq;

public class RequestUtilTest {

private static final String X_REAL_IP = "X-Real-IP";
private static final String X_FORWARDED_FOR = "X-Forwarded-For";

@Test
public void getRemoteIp() {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);

Mockito.when(request.getRemoteAddr()).thenReturn("127.0.0.1");
Assert.assertEquals(RequestUtil.getRemoteIp(request), "127.0.0.1");

Mockito.when(request.getHeader(eq(X_REAL_IP))).thenReturn("127.0.0.2");
Assert.assertEquals(RequestUtil.getRemoteIp(request), "127.0.0.2");

Mockito.when(request.getHeader(eq(X_FORWARDED_FOR))).thenReturn("127.0.0.3");
Assert.assertEquals(RequestUtil.getRemoteIp(request), "127.0.0.3");

Mockito.when(request.getHeader(eq(X_FORWARDED_FOR))).thenReturn("127.0.0.3, 127.0.0.4");
Assert.assertEquals(RequestUtil.getRemoteIp(request), "127.0.0.3");

Mockito.when(request.getHeader(eq(X_FORWARDED_FOR))).thenReturn("");
Assert.assertEquals(RequestUtil.getRemoteIp(request), "127.0.0.2");

Mockito.when(request.getHeader(eq(X_REAL_IP))).thenReturn("");
Assert.assertEquals(RequestUtil.getRemoteIp(request), "127.0.0.1");
}


@Test
public void getAppName() {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getHeader(eq(RequestUtil.CLIENT_APPNAME_HEADER))).thenReturn("test");
Assert.assertEquals(RequestUtil.getAppName(request), "test");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ public class NamingBase {
public static final String TEST_PORT_4_DOM_2 = "7070";
public static final String TETS_TOKEN_4_DOM_2 = "xyz";

static final String NAMING_CONTROLLER_PATH = "/nacos/v1/ns";

public static final int TEST_PORT = 8080;

public static String randomDomainName() {
Expand Down
169 changes: 169 additions & 0 deletions test/src/test/java/com/alibaba/nacos/test/naming/RestAPI_ITCase.java
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,162 @@ public void domServeStatus() throws Exception {
Assert.assertTrue(json.getJSONObject("data").getJSONArray("ips").size() > 0);
}

/**
* @TCDescription : 根据serviceName创建服务
* @TestStep :
* @ExpectResult :
*/
@Test
public void createService() throws Exception {
String serviceName = NamingBase.randomDomainName();
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.done(),
String.class,
HttpMethod.PUT);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());

namingServiceDelete(serviceName);
}

/**
* @TCDescription : 根据serviceName获取服务信息
* @TestStep :
* @ExpectResult :
*/
@Test
public void getService() throws Exception {
String serviceName = NamingBase.randomDomainName();
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.done(),
String.class,
HttpMethod.PUT);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());

//get service
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.done(),
String.class);

Assert.assertTrue(response.getStatusCode().is2xxSuccessful());

JSONObject json = JSON.parseObject(response.getBody());
Assert.assertEquals(serviceName, json.getString("name"));

namingServiceDelete(serviceName);
}

/**
* @TCDescription : 获取服务list信息
* @TestStep :
* @ExpectResult :
*/
@Test
public void listService() throws Exception {
String serviceName = NamingBase.randomDomainName();
//get service
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service/list",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("pageNo", "1")
.appendParam("pageSize", "15")
.done(),
String.class);

Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JSONObject json = JSON.parseObject(response.getBody());
int count = json.getIntValue("count");
Assert.assertTrue(count >= 0);

response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.done(),
String.class,
HttpMethod.PUT);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());

response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service/list",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("pageNo", "1")
.appendParam("pageSize", "15")
.done(),
String.class);

Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
json = JSON.parseObject(response.getBody());
Assert.assertEquals(count+1, json.getIntValue("count"));

namingServiceDelete(serviceName);
}

/**
* @TCDescription : 更新serviceName获取服务信息
* @TestStep :
* @ExpectResult :
*/
@Test
public void updateService() throws Exception {
String serviceName = NamingBase.randomDomainName();
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.done(),
String.class,
HttpMethod.PUT);
Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());

//update service
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("healthCheckMode", "server")
.appendParam("protectThreshold", "3")
.done(),
String.class,
HttpMethod.POST);

Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());

//get service
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.done(),
String.class);

Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
JSONObject json = JSON.parseObject(response.getBody());
System.out.println(json);
Assert.assertEquals(3.0f, json.getFloatValue("protectThreshold"), 0.0f);

namingServiceDelete(serviceName);
}

private void namingServiceDelete(String serviceName) {
//delete service
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.done(),
String.class,
HttpMethod.DELETE);

Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
Assert.assertEquals("ok", response.getBody());
}

private <T> ResponseEntity<T> request(String path, MultiValueMap<String, String> params, Class<T> clazz) {

HttpHeaders headers = new HttpHeaders();
Expand All @@ -596,6 +752,19 @@ private <T> ResponseEntity<T> request(String path, MultiValueMap<String, String>
builder.toUriString(), HttpMethod.GET, entity, clazz);
}

private <T> ResponseEntity<T> request(String path, MultiValueMap<String, String> params, Class<T> clazz, HttpMethod httpMethod) {

HttpHeaders headers = new HttpHeaders();

HttpEntity<?> entity = new HttpEntity<T>(headers);

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path)
.queryParams(params);

return this.restTemplate.exchange(
builder.toUriString(), httpMethod, entity, clazz);
}

private void prepareData() {

ResponseEntity<String> responseEntity = request("/nacos/v1/ns/api/regDom",
Expand Down
Loading

0 comments on commit 8fdbf68

Please sign in to comment.