|
| 1 | +/** |
| 2 | + * Copyright 2017, Google, Inc. |
| 3 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | + * you may not use this file except in compliance with the License. |
| 5 | + * You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software |
| 10 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | + * See the License for the specific language governing permissions and |
| 13 | + * limitations under the License. |
| 14 | + */ |
| 15 | + |
| 16 | +'use strict'; |
| 17 | + |
| 18 | +// [START appengine_metadata] |
| 19 | +const express = require('express'); |
| 20 | +const request = require('got'); |
| 21 | + |
| 22 | +const app = express(); |
| 23 | +app.enable('trust proxy'); |
| 24 | + |
| 25 | +const METADATA_NETWORK_INTERFACE_URL = 'http://metadata/computeMetadata/v1/' + |
| 26 | +'/instance/network-interfaces/0/access-configs/0/external-ip'; |
| 27 | + |
| 28 | +function getExternalIp () { |
| 29 | + const options = { |
| 30 | + headers: { |
| 31 | + 'Metadata-Flavor': 'Google' |
| 32 | + }, |
| 33 | + json: true |
| 34 | + }; |
| 35 | + |
| 36 | + return request(METADATA_NETWORK_INTERFACE_URL, options) |
| 37 | + .then((response) => response.body) |
| 38 | + .catch((err) => { |
| 39 | + if (err || err.statusCode !== 200) { |
| 40 | + console.log('Error while talking to metadata server, assuming localhost'); |
| 41 | + return 'localhost'; |
| 42 | + } |
| 43 | + return Promise.reject(err); |
| 44 | + }); |
| 45 | +} |
| 46 | + |
| 47 | +app.get('/', (req, res, next) => { |
| 48 | + getExternalIp() |
| 49 | + .then((externalIp) => { |
| 50 | + res.status(200).send(`External IP: ${externalIp}`).end(); |
| 51 | + }) |
| 52 | + .catch(next); |
| 53 | +}); |
| 54 | + |
| 55 | +const PORT = process.env.PORT || 8080; |
| 56 | +app.listen(PORT, () => { |
| 57 | + console.log(`App listening on port ${PORT}`); |
| 58 | + console.log('Press Ctrl+C to quit.'); |
| 59 | +}); |
| 60 | +// [END appengine_metadata] |
0 commit comments