├── .github └── workflows │ └── go.yml ├── .gitignore ├── LICENSE ├── README.md ├── assets ├── css │ ├── font.css │ └── style.css ├── fonts │ ├── S6u9w4BMUTPHh6UVSwiPGQ.woff2 │ ├── S6uyw4BMUTPHjx4wXg.woff2 │ ├── materialdesignicons-webfont﹖v=3.2.89.woff2 │ └── qkB9XvYC6trAT55ZBi1ueQVIjQTD-JrIH2G7nytkHRyQ8p4wUje6bg.woff2 └── libs │ ├── bootstrap │ ├── bootstrap.bundle.min.js │ └── bootstrap.min.css │ ├── icons │ ├── materialdesignicons.min.css │ └── unicons.js │ ├── jquery-1.12.4 │ └── jquery.min.js │ └── polyfills │ ├── gumshoe.polyfills.min.js │ └── smooth-scroll.polyfills.min.js ├── cfg.json.example ├── cfg.json.test ├── city.free.ipdb ├── control ├── controller ├── api.go ├── auth.go ├── midd.go ├── ratelimit.go └── route.go ├── cron └── sync.go ├── demo.jpg ├── g ├── cfg.go ├── const.go ├── load.go ├── logger.go ├── oauth2.go └── redis.go ├── geoip_test.go ├── gitversion ├── go.mod ├── go.sum ├── internal.csv ├── main.go ├── models ├── cfg.json.test ├── internal.mmdb.test ├── ip.go ├── ip_test.go ├── iprange.go ├── qqzengip.go ├── ratelimit.go ├── ratelimit_test.go ├── reader.go └── search.go ├── open-geoip.service ├── templates └── index.html └── util ├── auth.go ├── downloader.go └── string_util.go /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a golang project 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go 3 | 4 | name: Go 5 | 6 | on: 7 | push: 8 | branches: [ "main" ] 9 | pull_request: 10 | branches: [ "main" ] 11 | 12 | env: 13 | MAXMIND_LICENSE_KEY: ${{ secrets.MAXMIND_LICENSE_KEY }} 14 | 15 | jobs: 16 | build: 17 | runs-on: ubuntu-latest 18 | steps: 19 | - uses: actions/checkout@v3 20 | 21 | - name: Set up Go 22 | uses: actions/setup-go@v3 23 | with: 24 | go-version: 1.19 25 | 26 | - name: Build 27 | run: go build -v ./... 28 | 29 | - name: Test 30 | run: go test -v ./... 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | *.mmdb 8 | *.sha256 9 | *.dat 10 | *.tar.gz 11 | *.zip 12 | go-geoip 13 | 14 | 15 | # config 16 | *.json 17 | 18 | # logs 19 | logs/* 20 | 21 | # Output of the go coverage tool, specifically when used with LiteIDE 22 | *.out 23 | 24 | # Dependency directories (remove the comment below to include it) 25 | # vendor/ 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2023 East China Normal University 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Open-GeoIP 2 | Open-GeoIP: 简单且高性能的 IP 地址地理信息查询服务 3 | 4 | ![](https://github.com/ECNU/open-geoip/blob/main/demo.jpg?raw=true) 5 | 6 | - [Open-GeoIP](#open-geoip) 7 | - [安装运行](#安装运行) 8 | - [二进制直接运行](#二进制直接运行) 9 | - [systemctl 托管](#systemctl-托管) 10 | - [数据库自动更新](#数据库自动更新) 11 | - [maxmind](#maxmind) 12 | - [编译打包](#编译打包) 13 | - [定制页面](#定制页面) 14 | - [配置说明](#配置说明) 15 | - [内部 IP 地理数据库](#内部-ip-地理数据库) 16 | - [限流方案](#限流方案) 17 | - [高可用与扩展性](#高可用与扩展性) 18 | - [API](#api) 19 | - [myip](#myip) 20 | - [mylocation](#mylocation) 21 | - [searchapi](#searchapi) 22 | - [openapi](#openapi) 23 | - [benchmark](#benchmark) 24 | - [鸣谢](#鸣谢) 25 | 26 | ## 安装运行 27 | 28 | ### 二进制直接运行 29 | 在 [release](https://github.com/ECNU/open-geoip/releases) 中下载最新的 [release] 包,解压后直接运行即可。 30 | 31 | 注意:`release` 中内置的数据库文件来自于 [ipdb-go](https://github.com/ipipdotnet/ipdb-go) 中的 `city.free.ipdb`,仅供测试使用,不保证数据的准确性。 32 | 33 | 如应用于生产环境,请获取商用授权,或者[注册](https://www.maxmind.com/en/geolite2/signup) `maxmind` 的账号后,获取免费版的 `GeoLite2-City.mmdb` 数据库文件,并更新配置文件替换数据源为 `maxmind`。 34 | 35 | ``` 36 | tar -zxvf open-geoip-0.1.0-linux-amd64.tar.gz 37 | cd open-geoip/ 38 | ./control start 39 | ``` 40 | 访问你服务器的 80 端口即可使用。 41 | 42 | 43 | ### systemctl 托管 44 | 假定部署在 `/opt/open-geoip` 目录下,如果部署在其他目录修改 `open-geoip.service` 中的 `WorkingDirectory` 和 `ExecStart` 两个字段即可。 45 | ``` 46 | cp open-geoip.service /etc/systemd/system/ 47 | systemctl daemon-reload 48 | systemctl enable open-geoip 49 | systemctl start open-geoip 50 | ``` 51 | 52 | ### 数据库自动更新 53 | #### maxmind 54 | 如果需要自动更新 `mmdb` 数据库,只需要在[注册](https://www.maxmind.com/en/geolite2/signup)一个 `maxmind` 的账号,获得一个 [LicenseKey](https://www.maxmind.com/en/accounts/current/license-key) ,并将他配置到 `cfg.json` 中的 `AutoDownload.MaxmindLicenseKey` 中,或者配置到系统环境变量 `MAXMIND_LICENSE_KEY` 中即可。 55 | 56 | 57 | ### 编译打包 58 | ``` 59 | git clone https://github.com/ECNU/open-geoip.git 60 | cd open-geoip/ 61 | chmod +x control 62 | ./control pack 63 | ``` 64 | 65 | ### 定制页面 66 | 修改 `templates` 目录下的 `index.html` 即可,相关资源文件在 `assets` 目录下。 67 | 68 | ## 配置说明 69 | 70 | 根据 `cfg.json.example` 文件,创建 `cfg.json` 文件,再进一步根据自己的需要修改配置。 71 | 72 | ```json 73 | { 74 | "logger": { 75 | "dir": "logs/", 76 | "level": "DEBUG", 77 | "keepHours": 24 78 | }, 79 | "redis": { 80 | "dsn": "127.0.0.1:6379", 81 | "maxIdle": 5, 82 | "connTimeout": 5, 83 | "readTimeout": 5, 84 | "writeTimeout": 5, 85 | "password": "" 86 | }, 87 | "internal": { 88 | "source": "maxmind", 89 | "enable": false, 90 | "db": "GeoLite2-City.mmdb.test" 91 | }, 92 | "db": { 93 | "maxmind": "GeoLite2-City.mmdb", 94 | "qqzengip": "", 95 | "ipdb":"" 96 | }, 97 | "source": { 98 | "ipv4": "maxmind", 99 | "ipv6": "maxmind" 100 | }, 101 | "autoDownload":{ 102 | "enabled":false, 103 | "MaxmindLicenseKey":"", 104 | "targetFilePath":"", 105 | "timeout":3, 106 | "interval":24 107 | }, 108 | "rateLimit": { 109 | "enabled": false, 110 | "minute": 100, 111 | "hour": 1000, 112 | "day": 10000 113 | }, 114 | "http": { 115 | "listen": "0.0.0.0:80", 116 | "trustProxy": ["127.0.0.1", "::1"], 117 | "cors":["http://localhost"], 118 | "x-api-key": "this-is-key" 119 | } 120 | } 121 | ``` 122 | 123 | | 配置项 | 类型 | 说明 | 124 | |--------------------------------|--------|---------------------------------------------------------------------------------------------------------------------| 125 | | logger | object | 一个包含日志设置的部分 | 126 | | logger.dir | string | 存储日志文件的目录 | 127 | | logger.level | string | 日志的级别,比如DEBUG, INFO, WARN, 或ERROR | 128 | | logger.keepHours | number | 保留日志文件的小时数,之后删除 | 129 | | redis | object | redis 配置参数,配合限流策略使用 | 130 | | redis.dsn | string | redis 的连接地址 | 131 | | redis.maxIdle | number | redis 的最大空闲连接数 | 132 | | redis.connTimeout | number | redis 的连接超时时间,单位是 second | 133 | | redis.readTimeout | number | redis 的读取超时时间,单位是 second | 134 | | redis.writeTimeout | number | redis 的写入超时时间,单位是 second | 135 | | redis.password | string | redis 的密码 | 136 | | internal | object | 内部数据库参数 | 137 | | internal.enabled | bool | 开启内部数据库 | 138 | | internal.source | string | 内部数据库来源 | 139 | | internal.db | string | 内部数据库文件路径 140 | | db | object | 一个包含数据库设置的部分 | 141 | | db.maxmind | string | MaxMind GeoLite2数据库的文件的路径,如果 autDownload 配置为 true,那么这里的配置不会生效 | 142 | | db.qqzengip | string | qqzengip数据库的文件的路径 | 143 | | db.ipdb | string | ipip.net数据库的文件的路径 | 144 | | source | object | 一个包含IP信息来源设置的部分 | 145 | | source.ipv4 | string | IPv4信息的来源,可配置为 [maxmind](https://www.maxmind.com)/[qqzengip](https://www.qqzeng.com/)/[ipdb](https://www.ipip.net/) | 146 | | source.ipv6 | string | IPv6信息的来源,可配置为 [maxmind](https://www.maxmind.com)/[qqzengip](https://www.qqzeng.com/)/[ipdb](https://www.ipip.net/) | 147 | | autoDownload | object | 一个包含自动更新数据库的设置的部分 | 148 | | autoDownload.enabled | bool | 是否启用自动更新数据库 | 149 | | autoDownload.MaxmindLicenseKey | string | MaxMind License Key,用于自动更新 `MaxMind GeoLite2` 数据库,也可以配置在环境变量 `MAXMIND_LICENSE_KEY` 中。如果都没有配置,那么 `maxmind` 的自动更新会报错 | 150 | | autoDownload.targetFilePath | string | 自动更新数据库的目标文件路径,如果不配置此参数,默认值是 `./`,自动更新数据库会下载到这个目录 | 151 | | autoDownload.timeout | number | 自动更新数据库的超时时间,单位是 second,如果不配置此参数,默认值是 3 | 152 | | autoDownload.interval | number | 自动更新数据库的间隔时间,单位是 hour,如果不配置此参数,默认值是24 | 153 | | rateLimit | object | 一个包含限流设置的部分 | 154 | | rateLimit.enabled | bool | 是否启用限流策略 | 155 | | rateLimit.minute | number | 每分钟最多访问次, 0 表示不限制数 | 156 | | rateLimit.hour | number | 每小时最多访问次, 0 表示不限制数 | 157 | | rateLimit.day | number | 每天最多访问次, 0 表示不限制数 | 158 | | http | object | 一个包含HTTP服务器设置的部分 | 159 | | http.listen | string | HTTP服务器监听的地址和端口 | 160 | | http.trustProxy | array | 被信任的代理的IP地址的数组,当服务被发布在反向代理后时必须正确配置,否则无法正确获取到 xff 的地址。 | 161 | | http.cors | array | 允许跨域访问的域名列表,配置内的域名可以跨域访问 `/myip` 和 `/myip/format` 接口 | 162 | | http.x-api-key | string | 访问 openapi 接口所需的 API 密钥 | | 163 | ## 内部 IP 地理数据库 164 | 165 | Open-GeoIP 允许以导入的方式,构建企业内部自己的 IP 地理数据库,以便于查询内部 IP 地址的物理位置。 166 | 167 | 导入的格式是 `csv`,内容如下所示,项目中已经存在一个 `internal.csv` 的示例文件,可以参考。 168 | 169 | | continent | country | province | city | district | isp | areaCode | countryCode | countryEnglish | longitude | latitude | ip_subnet | 170 | | --------- | ------- | -------- | ---- | -------- | --- | -------- | ----------- | -------------- | --------- | -------- | --------- | 171 | | | | | | 保留 | 回环地址 | | | | | | 127.0.0.0/8 | 172 | | 亚洲 | 中国 | 上海 | 上海 | 开源教育 | 企业内网 | 310000 | CN | China ||| 10.0.0.0/8 | 173 | | 亚洲 | 中国 | 上海 | 上海 | 开源教育 | 企业内网 ||| CN || China ||| 192.168.0.0/16 | 174 | | 亚洲 ||| 中国 || 上海 || 上海 || 开源教育 || 企业内网 ||| 310000 || CN || China ||| 172.16.0.0/12 | 175 | | 亚洲 ||| 中国 || 上海 || 上海 || 开源教育 || 企业内网 ||| 310000 || CN || China |||| fd00::/8 | 176 | 177 | 178 | 在启动 Open-GeoIP 之前,执行 `-csv` 命令即可导入内部数据库,此时默认会生成一个 `internal.mmdb` 文件。 179 | ``` 180 | ./open-geoip -csv internal.csv 181 | ``` 182 | 在配置文件中,修改 `internal.mmdb` 的相关配置,将其开启即可。 183 | 184 | ```json 185 | "internaldb": { 186 | "source": "maxmind", 187 | "enabled": true, 188 | "db": "internal.mmdb" 189 | } 190 | ``` 191 | 192 | 193 | ## 限流方案 194 | Open-GeoIP 通过 redis 记录每个IP地址的访问次数,当超过阈值时,对该IP进行限制访问。支持分钟,小时,天 三种颗粒的计数策略,可以通过配置文件中的 ratelimit 的部分进行配置,以下示例表示开启了限流策略,并限制了每分钟最多访问 100 次,每小时最多访问 1000 次,每天最多访问 10000 次。 195 | 196 | ```json 197 | "rateLimit": { 198 | "enabled": true, 199 | "minute": 100, 200 | "hour": 1000, 201 | "day": 10000 202 | }, 203 | ``` 204 | 205 | ## 高可用与扩展性 206 | Open-GeoIP 是无状态的,因此可以任意的进行横向扩展并通过负载均衡实现高可用。在启用限流方案时,多个 Open-GeoIP 可以通过共享同一个 Redis 服务实现限流计数的一致性。 207 | 208 | ## API 209 | ### myip 210 | 211 | myip 的接口用于返回请求者的 IP 地址,对于一些无浏览器的终端,可以使用这个接口方便的获取自身的IP地址信息(特别是 nat 后的)。 212 | 213 | 它也可以被配置了 CORS 的网站通过前端调用 214 | 215 | 提供了简单字符串与 json 格式化两种风格接口。 216 | 217 | ``` 218 | # curl http://localhost/myip 219 | # 192.168.0.100 220 | ``` 221 | 222 | ``` 223 | # curl http://localhost/myip/format 224 | # {"errCode":0,"errMsg":"success","requestId":"0f40823e-04ce-4def-9af2-71e7e1403ec8","data":{"ip":"192.168.0.100"}} 225 | ``` 226 | 227 | ### mylocation 228 | 229 | mylocation 的接口用于返回请求者的 IP 地址对应的物理位置。 230 | 231 | 它也可以被配置了 CORS 的网站通过前端调用 232 | 233 | 提供了简单字符串与 json 格式化两种风格接口。 234 | 235 | ``` 236 | # curl http://localhost/mylocation 237 | # 保留地址 238 | ``` 239 | 240 | ``` 241 | # curl http://localhost/mylocation/format 242 | # {"errCode":0,"errMsg":"success","requestId":"c2e8c50e-b55f-455a-a9d4-d209acd20ab9","data":{"ip":"::1","continent":"保留地址","country":"","province":"","city":"","district":"","isp":"","areaCode":"","countryEnglish":"","countryCode":"","longitude":"","latitude":""}} 243 | ``` 244 | 245 | ### searchapi 246 | searchapi 接口面向浏览器,提供了一个 IP 地址的查询接口,并输出转换好的字符串以简化前端解析。 247 | 248 | 这个接口受验证码(todo)和限流措施的保护,以防范可能的恶意爬虫 249 | 250 | 他访问的路径是 `http://localhost/ip` 251 | 252 | ### openapi 253 | openapi 接口面向第三方应用,提供了一个 IP 地址的查询接口,通过 X-API-KEY 进行授权校验。 254 | 255 | 建议在多租户的情况下,进一步通过 API 网关进行代理封装和授权分发。 256 | 257 | - request 258 | ``` 259 | curl -H "X-API-KEY: this-is-key" http://localhost/api/v1/network/ip?ip=2001:da8:8005:a405:250:56ff:feaf:8c28 260 | ``` 261 | 262 | - response 263 | ```json 264 | { 265 | "errCode": 0, 266 | "errMsg": "success", 267 | "requestId": "7ead62f7-3f15-4822-ad1e-cf7915a8299f", 268 | "data": { 269 | "ip": "2001:da8:8005:a405:250:56ff:feaf:8c28", 270 | "continent": "亚洲", 271 | "country": "中国", 272 | "province": "上海", 273 | "city": "上海", 274 | "district": "", 275 | "isp": "", 276 | "areaCode": "", 277 | "countryEnglish": "China", 278 | "countryCode": "CN", 279 | "longitude": "121.458100", 280 | "latitude": "31.222200" 281 | } 282 | } 283 | ``` 284 | 285 | 286 | ## benchmark 287 | 基于 `maxmind` 数据库,`web` 服务性能测试 288 | ``` 289 | # go test -bench=. -benchmem 290 | 291 | goos: linux 292 | goarch: amd64 293 | pkg: github.com/ECNU/open-geoip 294 | cpu: Intel(R) Xeon(R) Platinum 8369B CPU @ 2.70GHz 295 | BenchmarkIndex-2 244190 4271 ns/op 10000 B/op 15 allocs/op 296 | BenchmarkSeachAPIForIPv4-2 782768 1741 ns/op 1904 B/op 15 allocs/op 297 | BenchmarkSeachAPIForIPv6-2 818250 1744 ns/op 1904 B/op 15 allocs/op 298 | BenchmarkOpenAPIForIPv4-2 394813 3383 ns/op 2592 B/op 23 allocs/op 299 | BenchmarkOpenAPIForIPv6-2 391868 3378 ns/op 2592 B/op 23 allocs/op 300 | PASS 301 | ok github.com/ECNU/open-geoip 7.044s 302 | ``` 303 | 304 | ## 鸣谢 305 | 306 | 本项目的一些主要功能使用了以下开源项目,更多的依赖详见 `go.mod` 。 307 | 308 | 感谢他们的开源精神。 309 | 310 | - `web` 服务 —— [gin](https://github.com/gin-gonic/gin) 311 | - `maxmind` 解析 —— [geoip2-golang](https://github.com/oschwald/geoip2-golang) 312 | - `maxming` 自动更新 —— [go-geoip](https://github.com/pieterclaerhout/go-geoip) 313 | - `ipdb` 解析 —— [ipdb-go](https://github.com/ipipdotnet/ipdb-go) 314 | - `qqzengip` 解析 —— [qqzeng-ip](https://https://github.com/zengzhan/qqzeng-ip) -------------------------------------------------------------------------------- /assets/css/font.css: -------------------------------------------------------------------------------- 1 | 2 | /* latin */ 3 | @font-face { 4 | font-family: 'Karla'; 5 | font-style: normal; 6 | font-weight: 400; 7 | font-display: swap; 8 | src: url(../fonts/qkB9XvYC6trAT55ZBi1ueQVIjQTD-JrIH2G7nytkHRyQ8p4wUje6bg.woff2) format('woff2'); 9 | unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; 10 | } 11 | /* latin */ 12 | @font-face { 13 | font-family: 'Karla'; 14 | font-style: normal; 15 | font-weight: 500; 16 | font-display: swap; 17 | src: url(../fonts/qkB9XvYC6trAT55ZBi1ueQVIjQTD-JrIH2G7nytkHRyQ8p4wUje6bg.woff2) format('woff2'); 18 | unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; 19 | } 20 | /* latin */ 21 | @font-face { 22 | font-family: 'Lato'; 23 | font-style: normal; 24 | font-weight: 400; 25 | font-display: swap; 26 | src: url(../fonts/S6uyw4BMUTPHjx4wXg.woff2) format('woff2'); 27 | unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; 28 | } 29 | /* latin */ 30 | @font-face { 31 | font-family: 'Lato'; 32 | font-style: normal; 33 | font-weight: 700; 34 | font-display: swap; 35 | src: url(../fonts/S6u9w4BMUTPHh6UVSwiPGQ.woff2) format('woff2'); 36 | unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; 37 | } 38 | -------------------------------------------------------------------------------- /assets/css/style.css: -------------------------------------------------------------------------------- 1 | @import url("font.css?family=Karla:wght@400;500&family=Lato:wght@400;700&display=swap"); 2 | 3 | body { 4 | font-family: 'Karla', sans-serif; 5 | overflow-x: hidden !important; 6 | position: relative; 7 | color: #404b67 8 | } 9 | 10 | h1, h2, h3, h4, h5, h6 { 11 | font-family: 'Lato', sans-serif; 12 | font-weight: 700; 13 | line-height: 1.3 14 | } 15 | 16 | .btn, .btn:focus, button, button:focus { 17 | outline: none !important 18 | } 19 | 20 | a { 21 | text-decoration: none !important; 22 | outline: 0 23 | } 24 | 25 | p { 26 | font-size: 17px; 27 | line-height: 26px 28 | } 29 | 30 | .row > * { 31 | position: relative 32 | } 33 | 34 | .section { 35 | padding-top: 90px; 36 | padding-bottom: 90px; 37 | position: relative 38 | } 39 | 40 | .bg-lightan { 41 | background-color: #fefefe; 42 | } 43 | 44 | hr { 45 | border-top: 1px solid #808eb1; 46 | margin: 0 47 | } 48 | 49 | .navbar-brand { 50 | color: #404b67; 51 | padding-top: 0.3125rem; 52 | padding-bottom: 0.3125rem; 53 | margin-right: 1rem; 54 | font-size: 1.25rem; 55 | text-decoration: none; 56 | white-space: nowrap; 57 | } 58 | 59 | .line-height_1_4 { 60 | line-height: 1.4 61 | } 62 | 63 | .line-height_1_6 { 64 | line-height: 1.6 65 | } 66 | 67 | .line-height_1_8 { 68 | line-height: 1.8 69 | } 70 | 71 | .fw-normal { 72 | font-weight: 500 !important 73 | } 74 | 75 | .fw-bold { 76 | font-weight: 600 !important 77 | } 78 | 79 | .btn { 80 | padding: 10px 20px; 81 | font-size: 15px; 82 | letter-spacing: .5px; 83 | transition: all .5s 84 | } 85 | 86 | .btn:focus { 87 | box-shadow: none 88 | } 89 | 90 | .btn:hover { 91 | transform: translateY(-5px) 92 | } 93 | 94 | .btn:hover:before { 95 | opacity: 1 96 | } 97 | 98 | .btn-sm { 99 | padding: 8px 12px; 100 | font-size: 12px 101 | } 102 | 103 | .shadow { 104 | box-shadow: 0 30px 30px 0 rgba(64, 75, 103, 0.06) !important 105 | } 106 | 107 | .text-primary { 108 | color: #1e57c7 !important 109 | } 110 | 111 | .border-primary { 112 | color: #1e57c7 !important 113 | } 114 | 115 | .btn-primary { 116 | background: #1e57c7; 117 | border-color: #1e57c7 !important 118 | } 119 | 120 | .btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .btn-primary.focus, .btn-primary:not(:disabled):not(.disabled):active, .btn-primary:not(:disabled):not(.disabled):active:focus, .btn-primary .open > .dropdown-toggle.btn-primary { 121 | background: #1b4fb5; 122 | border-color: #1b4fb5; 123 | box-shadow: 0 8px 20px -6px rgba(30, 87, 199, 0.6) 124 | } 125 | 126 | .home-overlay { 127 | height: 100%; 128 | width: 100%; 129 | background: linear-gradient(-45deg, #f3f3f3, #efefef, #f2f2f2, #efefef) 0 0; 130 | background-size: 600% 600%; 131 | position: absolute; 132 | animation: hoBg 6s ease infinite; 133 | right: 0; 134 | bottom: 0; 135 | left: 0; 136 | top: 0; 137 | } 138 | 139 | .home-title { 140 | max-width: 700px; 141 | font-size: 36px; 142 | margin: 0 auto 143 | } 144 | 145 | .home-desc { 146 | max-width: 600px; 147 | margin: auto 148 | } 149 | 150 | .form-select { 151 | color: #676f86 !important 152 | } 153 | 154 | .home-form { 155 | background: #fff; 156 | padding: 20px 21px; 157 | box-shadow: 0 8px 20px 10px rgba(64, 75, 103, 0.06); 158 | } 159 | 160 | .home-form .form-control { 161 | border: 1px solid #dfe9f1; 162 | height: 54px !important; 163 | font-size: 15px; 164 | border-radius: .25rem 165 | } 166 | 167 | .home-form .form-control ::placeholder { 168 | color: #676f86 169 | } 170 | 171 | .home-form .form-control:focus { 172 | border-color: #e4eef7 173 | } 174 | 175 | .home-form .home-button .btn { 176 | padding-top: 15px; 177 | padding-bottom: 15px 178 | } 179 | 180 | textarea.form-control { 181 | height: auto !important 182 | } 183 | 184 | .form-control { 185 | box-shadow: none !important; 186 | height: 42px; 187 | padding-left: 20px; 188 | border: 1px solid #dfe9f1; 189 | font-size: 16px; 190 | border-radius: 5px 191 | } 192 | 193 | .form-control:focus { 194 | border-color: #e4eef7 195 | } 196 | 197 | .bg-footer { 198 | padding: 30px 0; 199 | } 200 | 201 | .footer-link a { 202 | color: #808eb1; 203 | line-height: 38px; 204 | font-size: 17px; 205 | -webkit-transition: all .5s; 206 | background-color: transparent; 207 | transition: all .5s 208 | } 209 | 210 | .footer-link a:hover { 211 | color: #1e57c7 212 | } 213 | 214 | .footer-social i { 215 | width: 36px; 216 | height: 36px; 217 | display: inline-block; 218 | line-height: 36px; 219 | border-radius: 50%; 220 | text-align: center; 221 | background: #1e57c7; 222 | font-size: 15px; 223 | color: #fff 224 | } 225 | 226 | @media (min-width: 200px) and (max-width: 1024px) { 227 | .home-title { 228 | font-size: 32px 229 | } 230 | 231 | .logo .logo-light { 232 | display: none 233 | } 234 | 235 | .logo .logo-dark { 236 | display: inline-block 237 | } 238 | 239 | } 240 | 241 | @media (max-width: 768px) { 242 | 243 | } 244 | 245 | @media (min-width: 1200px) { 246 | .container { 247 | max-width: 1140px !important 248 | } 249 | } 250 | 251 | @keyframes hoBg { 252 | 0% { 253 | background-position: 0 50%; 254 | } 255 | 50% { 256 | background-position: 100% 50%; 257 | } 258 | 100% { 259 | background-position: 0 50%; 260 | } 261 | } -------------------------------------------------------------------------------- /assets/fonts/S6u9w4BMUTPHh6UVSwiPGQ.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ECNU/open-geoip/1eb64cd64c4856c5e2624e9d19b205c71073e350/assets/fonts/S6u9w4BMUTPHh6UVSwiPGQ.woff2 -------------------------------------------------------------------------------- /assets/fonts/S6uyw4BMUTPHjx4wXg.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ECNU/open-geoip/1eb64cd64c4856c5e2624e9d19b205c71073e350/assets/fonts/S6uyw4BMUTPHjx4wXg.woff2 -------------------------------------------------------------------------------- /assets/fonts/materialdesignicons-webfont﹖v=3.2.89.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ECNU/open-geoip/1eb64cd64c4856c5e2624e9d19b205c71073e350/assets/fonts/materialdesignicons-webfont﹖v=3.2.89.woff2 -------------------------------------------------------------------------------- /assets/fonts/qkB9XvYC6trAT55ZBi1ueQVIjQTD-JrIH2G7nytkHRyQ8p4wUje6bg.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ECNU/open-geoip/1eb64cd64c4856c5e2624e9d19b205c71073e350/assets/fonts/qkB9XvYC6trAT55ZBi1ueQVIjQTD-JrIH2G7nytkHRyQ8p4wUje6bg.woff2 -------------------------------------------------------------------------------- /assets/libs/icons/unicons.js: -------------------------------------------------------------------------------- 1 | !function(t){var r={};function e(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,e),o.l=!0,o.exports}e.m=t,e.c=r,e.d=function(t,r,n){e.o(t,r)||Object.defineProperty(t,r,{enumerable:!0,get:n})},e.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},e.t=function(t,r){if(1&r&&(t=e(t)),8&r)return t;if(4&r&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(e.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&r&&"string"!=typeof t)for(var o in t)e.d(n,o,function(r){return t[r]}.bind(null,o));return n},e.n=function(t){var r=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(r,"a",r),r},e.o=function(t,r){return Object.prototype.hasOwnProperty.call(t,r)},e.p="script/monochrome/",e(e.s=0)}([function(t,r,e){e(1),t.exports=e(2)},function(t,r,e){var n=function(t){"use strict";var r,e=Object.prototype,n=e.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},i=o.iterator||"@@iterator",a=o.asyncIterator||"@@asyncIterator",c=o.toStringTag||"@@toStringTag";function u(t,r,e,n){var o=r&&r.prototype instanceof m?r:m,i=Object.create(o.prototype),a=new k(n||[]);return i._invoke=function(t,r,e){var n=l;return function(o,i){if(n===h)throw new Error("Generator is already running");if(n===p){if("throw"===o)throw i;return G()}for(e.method=o,e.arg=i;;){var a=e.delegate;if(a){var c=_(a,e);if(c){if(c===y)continue;return c}}if("next"===e.method)e.sent=e._sent=e.arg;else if("throw"===e.method){if(n===l)throw n=p,e.arg;e.dispatchException(e.arg)}else"return"===e.method&&e.abrupt("return",e.arg);n=h;var u=s(t,r,e);if("normal"===u.type){if(n=e.done?p:f,u.arg===y)continue;return{value:u.arg,done:e.done}}"throw"===u.type&&(n=p,e.method="throw",e.arg=u.arg)}}}(t,e,a),i}function s(t,r,e){try{return{type:"normal",arg:t.call(r,e)}}catch(t){return{type:"throw",arg:t}}}t.wrap=u;var l="suspendedStart",f="suspendedYield",h="executing",p="completed",y={};function m(){}function d(){}function v(){}var g={};g[i]=function(){return this};var w=Object.getPrototypeOf,x=w&&w(w(P([])));x&&x!==e&&n.call(x,i)&&(g=x);var b=v.prototype=m.prototype=Object.create(g);function L(t){["next","throw","return"].forEach((function(r){t[r]=function(t){return this._invoke(r,t)}}))}function E(t){var r;this._invoke=function(e,o){function i(){return new Promise((function(r,i){!function r(e,o,i,a){var c=s(t[e],t,o);if("throw"!==c.type){var u=c.arg,l=u.value;return l&&"object"==typeof l&&n.call(l,"__await")?Promise.resolve(l.__await).then((function(t){r("next",t,i,a)}),(function(t){r("throw",t,i,a)})):Promise.resolve(l).then((function(t){u.value=t,i(u)}),(function(t){return r("throw",t,i,a)}))}a(c.arg)}(e,o,r,i)}))}return r=r?r.then(i,i):i()}}function _(t,e){var n=t.iterator[e.method];if(n===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=r,_(t,e),"throw"===e.method))return y;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return y}var o=s(n,t.iterator,e.arg);if("throw"===o.type)return e.method="throw",e.arg=o.arg,e.delegate=null,y;var i=o.arg;return i?i.done?(e[t.resultName]=i.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=r),e.delegate=null,y):i:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,y)}function O(t){var r={tryLoc:t[0]};1 in t&&(r.catchLoc=t[1]),2 in t&&(r.finallyLoc=t[2],r.afterLoc=t[3]),this.tryEntries.push(r)}function j(t){var r=t.completion||{};r.type="normal",delete r.arg,t.completion=r}function k(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function P(t){if(t){var e=t[i];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,a=function e(){for(;++o=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),s=n.call(a,"finallyLoc");if(u&&s){if(this.prev=0;--e){var o=this.tryEntries[e];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--r){var e=this.tryEntries[r];if(e.finallyLoc===t)return this.complete(e.completion,e.afterLoc),j(e),y}},catch:function(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e.tryLoc===t){var n=e.completion;if("throw"===n.type){var o=n.arg;j(e)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:P(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=r),y}},t}(t.exports);try{regeneratorRuntime=n}catch(t){Function("r","regeneratorRuntime = r")(n)}},function(t,r){var e="https://unicons.iconscout.com/release/".concat("v2.0.1","/svg/monochrome/");window.Unicons=window.Unicons||{},window.Unicons.DEBUG=window.Unicons.DEBUG||!1;var n=function(t){t.forEach((function(t){fetch("".concat(e).concat(t,".svg")).then((function(t){return t.text()})).then((function(r){return function(t,r){for(var n=document.getElementsByClassName("".concat("uim-").concat(t));n.length>0;){var o=n[0],i=document.createElement("span");i.innerHTML=r,i.classList.add("uim-svg"),i.firstChild.setAttribute("width","1em"),i.style.cssText=o.style.cssText,o.classList.contains("uim-white")&&(i.style.mask="url(".concat(e).concat(t,".svg)"),i.style.webkitMask="url(".concat(e).concat(t,".svg)"),i.style.background="white"),o.replaceWith(i)}}(t,r)}))}))},o=function(){var t=document.getElementsByClassName("uim"),r=[];window.Unicons.DEBUG&&console.log("Replacing ".concat(t.length," icons"));for(var e=0;e-1){var e=t.toLocaleLowerCase().replace("uim-","");-1===r.indexOf(e)&&r.push(e)}}))}n(r)};window.onload=o,window.Unicons.refresh=o;var i=document.createElement("style");i.innerHTML=":root {\n --uim-primary-opacity: 1;\n --uim-secondary-opacity: 0.70;\n --uim-tertiary-opacity: 0.50;\n --uim-quaternary-opacity: 0.25;\n --uim-quinary-opacity: 0;\n}\n.uim-svg {\n display: inline-block;\n height: 1em;\n vertical-align: -0.125em;\n font-size: inherit;\n fill: var(--uim-color, currentColor);\n}\n.uim-svg svg {\n display: inline-block;\n}\n.uim-primary {\n opacity: var(--uim-primary-opacity);\n}\n.uim-secondary {\n opacity: var(--uim-secondary-opacity);\n}\n.uim-tertiary {\n opacity: var(--uim-tertiary-opacity);\n}\n.uim-quaternary {\n opacity: var(--uim-quaternary-opacity);\n}\n.uim-quinary {\n opacity: var(--uim-quinary-opacity);\n}",document.head.appendChild(i)}]); 2 | //# sourceMappingURL=bundle.js.map -------------------------------------------------------------------------------- /assets/libs/polyfills/gumshoe.polyfills.min.js: -------------------------------------------------------------------------------- 1 | /* gumshoe v4.0.0 | (c) 2019 Chris Ferdinandi | MIT License | http://github.com/cferdinandi/gumshoe */ 2 | Element.prototype.closest||(Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector),Element.prototype.closest=function(b){var a=this;if(!document.documentElement.contains(this)){return null}do{if(a.matches(b)){return a}a=a.parentElement}while(null!==a);return null}),(function(){if("function"==typeof window.CustomEvent){return !1}function a(d,b){b=b||{bubbles:!1,cancelable:!1,detail:void 0};var c=document.createEvent("CustomEvent");return c.initCustomEvent(d,b.bubbles,b.cancelable,b.detail),c}a.prototype=window.Event.prototype,window.CustomEvent=a})(),(function(b,a){"function"==typeof define&&define.amd?define([],(function(){return a(b)})):"object"==typeof exports?module.exports=a(b):b.Gumshoe=a(b)})("undefined"!=typeof global?global:"undefined"!=typeof window?window:this,(function(m){var f={navClass:"active",contentClass:"active",nested:!1,nestedClass:"active",offset:0,reflow:!1,events:!0},h=function(p,a,c){if(c.settings.events){var i=new CustomEvent(p,{bubbles:!0,cancelable:!0,detail:c});a.dispatchEvent(i)}},j=function(c){var a=0;if(c.offsetParent){for(;c;){a+=c.offsetTop,c=c.offsetParent}}return a>=0?a:0},l=function(a){a.sort((function(i,c){return j(i.content)i},g=function(i,a){if(a.nested){var c=i.parentNode.closest("li");c&&(c.classList.remove(a.nestedClass),g(c,a))}},d=function(i,a){if(i){var c=i.nav.closest("li");c&&(c.classList.remove(a.navClass),i.content.classList.remove(a.contentClass),g(c,a),h("gumshoeDeactivate",c,{link:i.nav,content:i.content,settings:a}))}},b=function(i,a){if(a.nested){var c=i.parentNode.closest("li");c&&(c.classList.add(a.nestedClass),b(c,a))}};return function(s,n){var q,w,e,a,x,r={};r.setup=function(){q=document.querySelectorAll(s),w=[],Array.prototype.forEach.call(q,(function(o){var i=document.getElementById(decodeURIComponent(o.hash.substr(1)));i&&w.push({nav:o,content:i})})),l(w)},r.detect=function(){var i=(function(u,o){for(var p=u.length-1;p>=0;p--){if(k(u[p].content,o)){return u[p]}}})(w,x);i?e&&i.content===e.content||(d(e,x),(function(v,p){if(v){var u=v.nav.closest("li");u&&(u.classList.add(p.navClass),v.content.classList.add(p.contentClass),b(u,p),h("gumshoeActivate",u,{link:v.nav,content:v.content,settings:p}))}})(i,x),e=i):e&&(d(e,x),e=null)};var t=function(i){a&&m.cancelAnimationFrame(a),a=m.requestAnimationFrame(r.detect)},c=function(i){a&&m.cancelAnimationFrame(a),a=m.requestAnimationFrame((function(){l(),r.detect()}))};return r.destroy=function(){e&&d(e),m.removeEventListener("scroll",t,!1),x.reflow&&m.removeEventListener("resize",c,!1),w=null,q=null,e=null,a=null,x=null},r.init=function(i){x=(function(){var o={};return Array.prototype.forEach.call(arguments,(function(p){for(var u in p){if(!p.hasOwnProperty(u)){return}o[u]=p[u]}})),o})(f,i||{}),r.setup(),r.detect(),m.addEventListener("scroll",t,!1),x.reflow&&m.addEventListener("resize",c,!1)},r.init(n),r}})); -------------------------------------------------------------------------------- /assets/libs/polyfills/smooth-scroll.polyfills.min.js: -------------------------------------------------------------------------------- 1 | /* SmoothScroll v16.1.4 | (c) 2020 Chris Ferdinandi | MIT License | http://github.com/cferdinandi/smooth-scroll */ 2 | !function(a,b){"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define(b):(a=a||self).SmoothScroll=b()}(this,(function(){window.Element&&!Element.prototype.closest&&(Element.prototype.closest=function(a){var l,i=(this.document||this.ownerDocument).querySelectorAll(a),k=this;do{for(l=i.length;--l>=0&&i.item(l)!==k;){}}while(l<0&&(k=k.parentElement));return k}),function(){if("function"==typeof window.CustomEvent){return !1}function a(i,l){l=l||{bubbles:!1,cancelable:!1,detail:void 0};var k=document.createEvent("CustomEvent");return k.initCustomEvent(i,l.bubbles,l.cancelable,l.detail),k}a.prototype=window.Event.prototype,window.CustomEvent=a}(),function(){for(var a=0,k=["ms","moz","webkit","o"],i=0;i=1&&u<=31||127==u||0===m&&u>=48&&u<=57||1===m&&u>=48&&u<=57&&45===s?k+="\\"+u.toString(16)+" ":k+=u>=128||45===u||95===u||u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122?p.charAt(m):"\\"+p.charAt(m)}return"#"+k},g=function(){return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight,document.body.offsetHeight,document.documentElement.offsetHeight,document.body.clientHeight,document.documentElement.clientHeight)},d=function(a){return a?(i=a,parseInt(window.getComputedStyle(i).height,10)+a.offsetTop):0;var i},b=function(a,k,i){0===a&&document.body.focus(),i||(a.focus(),document.activeElement!==a&&(a.setAttribute("tabindex","-1"),a.focus(),a.style.outline="none"),window.scrollTo(0,k))},h=function(a,p,l,m){if(p.emitEvents&&"function"==typeof window.CustomEvent){var k=new CustomEvent(a,{bubbles:!0,detail:{anchor:l,toggle:m}});document.dispatchEvent(k)}};return function(a,q){var p,n,e,o,i={};i.cancelScroll=function(l){cancelAnimationFrame(o),o=null,l||h("scrollCancel",p)},i.animateScroll=function(H,t,L){i.cancelScroll();var F=j(p||c,L||{}),P="[object Number]"===Object.prototype.toString.call(H),D=P||!H.tagName?null:H;if(P||D){var J=window.pageYOffset;F.header&&!e&&(e=document.querySelector(F.header));var B,Q,N,K=d(e),z=P?H:function(u,y,w,v){var l=0;if(u.offsetParent){do{l+=u.offsetTop,u=u.offsetParent}while(u)}return l=Math.max(l-y-w,0),v&&(l=Math.min(l,g()-window.innerHeight)),l}(D,K,parseInt("function"==typeof F.offset?F.offset(H,t):F.offset,10),F.clip),s=z-J,m=g(),I=0,x=function(l,v){var u=v.speedAsDuration?v.speed:Math.abs(l/1000*v.speed);return v.durationMax&&u>v.durationMax?v.durationMax:v.durationMin&&u1?1:Q),window.scrollTo(0,Math.floor(N)),function(u,w){var v=window.pageYOffset;if(u==w||v==w||(J=m){return i.cancelScroll(!0),b(H,w,P),h("scrollStop",F,H,t),B=null,o=null,!0}}(N,z)||(o=window.requestAnimationFrame(G),B=l)};0===window.pageYOffset&&window.scrollTo(0,0),function(l,v,u){v||history.pushState&&u.updateURL&&history.pushState({smoothScroll:JSON.stringify(u),anchor:l.id},document.title,l===document.documentElement?"#top":"#"+l.id)}(H,P,F),"matchMedia" in window&&window.matchMedia("(prefers-reduced-motion)").matches?b(H,Math.floor(z),!1):(h("scrollStart",F,H,t),i.cancelScroll(!0),window.requestAnimationFrame(G))}};var r=function(l){if(!l.defaultPrevented&&!(0!==l.button||l.metaKey||l.ctrlKey||l.shiftKey)&&"closest" in l.target&&(n=l.target.closest(a))&&"a"===n.tagName.toLowerCase()&&!l.target.closest(p.ignore)&&n.hostname===window.location.hostname&&n.pathname===window.location.pathname&&/#/.test(n.href)){var s,m;try{s=f(decodeURIComponent(n.hash))}catch(l){s=f(n.hash)}if("#"===s){if(!p.topOnEmptyHash){return}m=document.documentElement}else{m=document.querySelector(s)}(m=m||"#top"!==s?m:document.documentElement)&&(l.preventDefault(),function(u){if(history.replaceState&&u.updateURL&&!history.state){var v=window.location.hash;v=v||"",history.replaceState({smoothScroll:JSON.stringify(u),anchor:v||window.pageYOffset},document.title,v||window.location.href)}}(p),i.animateScroll(m,n))}},k=function(){if(null!==history.state&&history.state.smoothScroll&&history.state.smoothScroll===JSON.stringify(p)){var l=history.state.anchor;"string"==typeof l&&l&&!(l=document.querySelector(f(history.state.anchor)))||i.animateScroll(l,null,{updateURL:!1})}};i.destroy=function(){p&&(document.removeEventListener("click",r,!1),window.removeEventListener("popstate",k,!1),i.cancelScroll(),p=null,n=null,e=null,o=null)};return function(){if(!("querySelector" in document&&"addEventListener" in window&&"requestAnimationFrame" in window&&"closest" in window.Element.prototype)){throw"Smooth Scroll: This browser does not support the required JavaScript methods and browser APIs."}i.destroy(),p=j(c,q||{}),e=p.header?document.querySelector(p.header):null,document.addEventListener("click",r,!1),p.updateURL&&p.popstate&&window.addEventListener("popstate",k,!1)}(),i}})); -------------------------------------------------------------------------------- /cfg.json.example: -------------------------------------------------------------------------------- 1 | { 2 | "logger": { 3 | "dir": "logs/", 4 | "level": "DEBUG", 5 | "keepHours": 24 6 | }, 7 | "redis": { 8 | "dsn": "127.0.0.1:6379", 9 | "maxIdle": 5, 10 | "connTimeout": 5, 11 | "readTimeout": 5, 12 | "writeTimeout": 5, 13 | "password": "" 14 | }, 15 | "internaldb": { 16 | "source": "maxmind", 17 | "auth":false, 18 | "enabled": false, 19 | "db": "internal.mmdb" 20 | }, 21 | "db": { 22 | "maxmind": "GeoLite2-City.mmdb", 23 | "qqzengip": "", 24 | "ipdb": "" 25 | }, 26 | "source": { 27 | "ipv4": "maxmind", 28 | "ipv6": "maxmind" 29 | }, 30 | "autoDownload": { 31 | "enabled": false, 32 | "MaxmindLicenseKey": "", 33 | "targetFilePath": "", 34 | "timeout": 3, 35 | "interval": 24 36 | }, 37 | "rateLimit": { 38 | "enabled": false, 39 | "minute": 100, 40 | "hour": 1000, 41 | "day": 10000 42 | }, 43 | "sso":{ 44 | "enabled":false, 45 | "authExpire":3600, 46 | "type":"oauth2" 47 | }, 48 | "oauth2":{ 49 | "enabled":false, 50 | "displayName":"统一身份认证", 51 | "redirectURL":"http://localhost/sso/callback/oauth2", 52 | "AuthAddr":"http://cas.example.org/cas/oauth2.0/authorize", 53 | "TokenAddr":"http://cas.example.org/cas/oauth2.0/accessToken", 54 | "UserinfoAddr":"http://cas.example.org/cas/oauth2.0/profile", 55 | "LogoutAddr":"https://cas.example.org/cas/logout?service=http://localhost/", 56 | "scopes":["exmaple-scope"], 57 | "clientId":"client_id", 58 | "clientSecret":"client_secret", 59 | "userinfoIsArray":false, 60 | "userinfoPrefix":"attributes", 61 | "attributes":{ 62 | "username":"userId", 63 | "nickname":"name" 64 | } 65 | }, 66 | "http": { 67 | "listen": "0.0.0.0:80", 68 | "trustProxy": ["127.0.0.1", "::1"], 69 | "cors": ["http://localhost"], 70 | "x-api-key": "this-is-key", 71 | "sessionOptions": { 72 | "path": "/", 73 | "domain": "localhost", 74 | "maxAge": 3600, 75 | "secure": false, 76 | "httpOnly": true 77 | } 78 | } 79 | } -------------------------------------------------------------------------------- /cfg.json.test: -------------------------------------------------------------------------------- 1 | { 2 | "logger": { 3 | "dir": "logs/", 4 | "level": "INFO", 5 | "keepHours": 24 6 | }, 7 | "internaldb": { 8 | "source": "maxmind", 9 | "enabled": false, 10 | "db": "internal.mmdb" 11 | }, 12 | "db": { 13 | "maxmind": "", 14 | "qqzengip": "", 15 | "ipdb":"city.free.ipdb" 16 | }, 17 | "source": { 18 | "ipv4": "ipdb", 19 | "ipv6": "ipdb" 20 | }, 21 | "AutoDownload":{ 22 | "enabled":false 23 | }, 24 | "http": { 25 | "listen": "0.0.0.0:80", 26 | "trustProxy": ["127.0.0.1", "::1"], 27 | "cors":["http://localhost"], 28 | "x-api-key": "this-is-key" 29 | } 30 | } -------------------------------------------------------------------------------- /city.free.ipdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ECNU/open-geoip/1eb64cd64c4856c5e2624e9d19b205c71073e350/city.free.ipdb -------------------------------------------------------------------------------- /control: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | WORKSPACE=$(cd $(dirname $0)/; pwd) 4 | cd $WORKSPACE 5 | 6 | mkdir -p var 7 | 8 | app=open-geoip 9 | conf=cfg.json 10 | pidfile=var/app.pid 11 | logfile=var/app.log 12 | 13 | function check_pid() { 14 | if [ -f $pidfile ];then 15 | pid=`cat $pidfile` 16 | if [ -n $pid ]; then 17 | running=`ps -p $pid|grep -v "PID TTY" |wc -l` 18 | return $running 19 | fi 20 | fi 21 | return 0 22 | } 23 | 24 | function start() { 25 | check_pid 26 | running=$? 27 | if [ $running -gt 0 ];then 28 | echo -n "$app now is running already, pid=" 29 | cat $pidfile 30 | return 1 31 | fi 32 | 33 | if ! [ -f $conf ];then 34 | echo "Config file $conf doesn't exist, creating one." 35 | cp cfg.example.json $conf 36 | fi 37 | nohup ./$app -c $conf &> $logfile & 38 | echo $! > $pidfile 39 | echo "$app started..., pid=$!" 40 | } 41 | 42 | function stop() { 43 | pid=`cat $pidfile` 44 | kill $pid 45 | echo "$app stoped..." 46 | } 47 | 48 | function restart() { 49 | stop 50 | sleep 1 51 | start 52 | } 53 | 54 | function status() { 55 | check_pid 56 | running=$? 57 | if [ $running -gt 0 ];then 58 | echo started 59 | else 60 | echo stoped 61 | fi 62 | } 63 | 64 | function tailf() { 65 | tail -f $logfile 66 | } 67 | 68 | function build() { 69 | go build 70 | if [ $? -ne 0 ]; then 71 | exit $? 72 | fi 73 | ./$app -v 74 | } 75 | 76 | function pack() { 77 | build 78 | git log -1 --pretty=%h > gitversion 79 | version=`./$app -v` 80 | file_list="assets templates control cfg.json cfg.json.example internal.csv city.free.ipdb $app" 81 | echo "...tar $app-$version.tar.gz <= $file_list" 82 | tar zcf $app-$version.tar.gz gitversion $file_list 83 | } 84 | 85 | 86 | function help() { 87 | echo "$0 build|pack|start|stop|restart|status|tail" 88 | } 89 | 90 | if [ "$1" == "" ]; then 91 | help 92 | elif [ "$1" == "stop" ];then 93 | stop 94 | elif [ "$1" == "start" ];then 95 | start 96 | elif [ "$1" == "restart" ];then 97 | restart 98 | elif [ "$1" == "status" ];then 99 | status 100 | elif [ "$1" == "tail" ];then 101 | tailf 102 | elif [ "$1" == "build" ];then 103 | build 104 | elif [ "$1" == "pack" ];then 105 | pack 106 | else 107 | help 108 | fi 109 | -------------------------------------------------------------------------------- /controller/api.go: -------------------------------------------------------------------------------- 1 | package controller 2 | 3 | import ( 4 | "net/http" 5 | "strings" 6 | 7 | "github.com/ECNU/open-geoip/g" 8 | "github.com/gin-contrib/sessions" 9 | 10 | "github.com/ECNU/open-geoip/models" 11 | 12 | "github.com/gin-gonic/gin" 13 | ) 14 | 15 | func geoIpApi(c *gin.Context) { 16 | isAuth := false 17 | ipAddr := c.Query("ip") 18 | // 去掉左右空格 19 | ipAddr = strings.TrimSpace(ipAddr) 20 | if !models.CheckIPValid(ipAddr) { 21 | c.String(http.StatusOK, "不是合法的IP地址") 22 | return 23 | } 24 | if err := models.SetQueryRateLimit(g.Config().RateLimit.Enabled, c.ClientIP()); err != nil { 25 | c.String(http.StatusOK, err.Error()) 26 | return 27 | } 28 | if g.Config().SSO.Enabled { 29 | session := sessions.Default(c) 30 | u := session.Get("username") 31 | if u != nil { 32 | isAuth = true 33 | } 34 | } 35 | 36 | c.String(http.StatusOK, models.SearchIP(ipAddr, false, isAuth).ToString()) 37 | } 38 | 39 | func getMyIP(c *gin.Context) { 40 | c.String(http.StatusOK, c.ClientIP()) 41 | } 42 | 43 | func getMyIPFormat(c *gin.Context) { 44 | res := map[string]string{ 45 | "ip": c.ClientIP(), 46 | } 47 | c.JSON(http.StatusOK, SuccessRes(res)) 48 | } 49 | 50 | func getMyLocation(c *gin.Context) { 51 | c.String(http.StatusOK, models.SearchIP(c.ClientIP(), true, false).ToString()) 52 | } 53 | 54 | func getMyLocationFormat(c *gin.Context) { 55 | c.JSON(http.StatusOK, SuccessRes(models.SearchIP(c.ClientIP(), true, false))) 56 | } 57 | 58 | func openGetIpApi(c *gin.Context) { 59 | ipAddr := c.Query("ip") 60 | if !models.CheckIPValid(ipAddr) { 61 | c.JSON(http.StatusOK, ErrorRes(ParamValueError, "不是合法的IP地址")) 62 | return 63 | } 64 | res := models.SearchIP(ipAddr, true, false) 65 | c.JSON(http.StatusOK, SuccessRes(res)) 66 | } 67 | -------------------------------------------------------------------------------- /controller/auth.go: -------------------------------------------------------------------------------- 1 | package controller 2 | 3 | import ( 4 | "context" 5 | "net/http" 6 | 7 | "github.com/ECNU/open-geoip/g" 8 | "github.com/ECNU/open-geoip/util" 9 | "github.com/gin-contrib/sessions" 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | func OauthAuth(c *gin.Context) { 14 | code := c.Request.FormValue("code") 15 | token, err := g.Oauth2Config.Exchange(context.Background(), code) 16 | if err != nil { 17 | c.String(http.StatusInternalServerError, "内部错误") 18 | } 19 | 20 | userInfo, err := util.OauthUserInfo(token.AccessToken) 21 | if err != nil { 22 | c.String(http.StatusInternalServerError, "内部错误") 23 | } 24 | 25 | session := sessions.Default(c) 26 | session.Set("username", userInfo.Username) 27 | session.Set("nickname", userInfo.Nickname) 28 | session.Save() 29 | 30 | c.Redirect(http.StatusMovedPermanently, "/") 31 | } 32 | 33 | func ssoLogout(c *gin.Context) { 34 | session := sessions.Default(c) 35 | session.Clear() 36 | session.Options(sessions.Options{MaxAge: -1}) 37 | session.Save() 38 | c.Redirect(http.StatusMovedPermanently, g.Config().Oauth2.LogoutAddr) 39 | } 40 | -------------------------------------------------------------------------------- /controller/midd.go: -------------------------------------------------------------------------------- 1 | package controller 2 | 3 | import ( 4 | "net/http" 5 | 6 | "github.com/ECNU/open-geoip/g" 7 | "github.com/gin-gonic/gin" 8 | uuid "github.com/satori/go.uuid" 9 | "github.com/toolkits/pkg/logger" 10 | ) 11 | 12 | // APIResult api 接口的数据结构 13 | type APIResult struct { 14 | ErrCode int64 `json:"errCode"` 15 | ErrMsg string `json:"errMsg"` 16 | RequestId string `json:"requestId"` 17 | Data interface{} `json:"data"` 18 | } 19 | 20 | const ( 21 | Success = 0 22 | ParamFormatError = 4001 23 | ParamValueError = 4002 24 | ParamMissError = 4003 25 | InternalAPIError = 5000 26 | ) 27 | 28 | var codeMsg = map[int64]string{ 29 | Success: "success", 30 | ParamFormatError: "参数校验错误", 31 | ParamValueError: "参数取值错误", 32 | ParamMissError: "缺失参数", 33 | InternalAPIError: "服务器内部错误", 34 | } 35 | 36 | // ErrorRes 请求异常时的返回 37 | func ErrorRes(code int64, msg string) (res APIResult) { 38 | res.ErrCode = code 39 | if msg == "" { 40 | res.ErrMsg = codeMsg[code] 41 | } else { 42 | res.ErrMsg = msg 43 | } 44 | res.RequestId = uuid.NewV4().String() 45 | return 46 | } 47 | 48 | // SuccessRes 请求正常时的返回 49 | func SuccessRes(data interface{}) (apiResult APIResult) { 50 | apiResult.ErrCode = 0 51 | apiResult.ErrMsg = "success" 52 | apiResult.RequestId = uuid.NewV4().String() 53 | apiResult.Data = data 54 | return 55 | } 56 | 57 | // XAPICheckMidd 校验X-API-KEY,供API网关代理这个接口 58 | func XAPICheckMidd(c *gin.Context) { 59 | key := c.Request.Header.Get("X-API-KEY") 60 | if !checkXApiKey(key) { 61 | logger.Warning(key, g.Config().Http.XAPIKey) 62 | c.JSON(http.StatusUnauthorized, ErrorRes(InternalAPIError, "")) 63 | c.Abort() 64 | return 65 | } 66 | c.Next() 67 | } 68 | 69 | func checkXApiKey(key string) bool { 70 | return key == g.Config().Http.XAPIKey 71 | } 72 | -------------------------------------------------------------------------------- /controller/ratelimit.go: -------------------------------------------------------------------------------- 1 | package controller 2 | 3 | import ( 4 | "net/http" 5 | 6 | "github.com/ECNU/open-geoip/models" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | func getRateLimit(c *gin.Context) { 12 | clientIP := c.Query("clientip") 13 | currentRateLimit, err := models.GetCurrentRateCount(clientIP) 14 | if err != nil { 15 | c.JSON(http.StatusInternalServerError, ErrorRes(InternalAPIError, err.Error())) 16 | return 17 | } 18 | c.JSON(http.StatusOK, SuccessRes(currentRateLimit)) 19 | } 20 | 21 | func clearRateLimit(c *gin.Context) { 22 | clientIP := c.Query("clientip") 23 | if err := models.ClearRateLimit(clientIP); err != nil { 24 | c.JSON(http.StatusInternalServerError, ErrorRes(InternalAPIError, err.Error())) 25 | return 26 | } 27 | c.JSON(http.StatusOK, SuccessRes(nil)) 28 | } 29 | -------------------------------------------------------------------------------- /controller/route.go: -------------------------------------------------------------------------------- 1 | package controller 2 | 3 | import ( 4 | "net/http" 5 | 6 | "github.com/ECNU/open-geoip/g" 7 | "github.com/ECNU/open-geoip/util" 8 | "github.com/gin-contrib/sessions" 9 | "github.com/gin-contrib/sessions/redis" 10 | "github.com/gin-gonic/gin" 11 | "github.com/toolkits/pkg/logger" 12 | ) 13 | 14 | func InitGin(listen string) (httpServer *http.Server) { 15 | if g.Config().Logger.Level == "DEBUG" { 16 | gin.SetMode((gin.DebugMode)) 17 | } else { 18 | gin.SetMode(gin.ReleaseMode) 19 | } 20 | r := gin.New() 21 | if g.Config().Logger.Level == "DEBUG" { 22 | r.Use(gin.Logger()) 23 | } 24 | r.Use(gin.Recovery()) 25 | 26 | r.SetTrustedProxies(g.Config().Http.TrustProxy) 27 | if g.Config().SSO.Enabled { 28 | store, err := redis.NewStore(10, "tcp", g.Config().Redis.Dsn, g.Config().Redis.Password, []byte("open-geoip")) 29 | if err != nil { 30 | panic(err) 31 | } 32 | store.Options(sessions.Options{ 33 | Path: g.Config().Http.SessionOptions.Path, 34 | Domain: g.Config().Http.SessionOptions.Domain, 35 | MaxAge: g.Config().Http.SessionOptions.MaxAge, 36 | Secure: g.Config().Http.SessionOptions.Secure, 37 | HttpOnly: g.Config().Http.SessionOptions.HttpOnly, 38 | }) 39 | r.Use(sessions.Sessions("mysession", store)) 40 | } 41 | 42 | r.GET("/version", func(c *gin.Context) { 43 | c.String(http.StatusOK, g.VERSION) 44 | }) 45 | Routes(r) 46 | 47 | httpServer = &http.Server{ 48 | Addr: g.Config().Http.Listen, 49 | Handler: r, 50 | } 51 | return 52 | } 53 | 54 | func Routes(r *gin.Engine) { 55 | r.LoadHTMLFiles("templates/index.html") 56 | r.Static("/assets", "assets") 57 | 58 | r.GET("/ip", geoIpApi) 59 | r.GET("/", index) 60 | 61 | myip := r.Group("/") 62 | myip.Use(CORS()) 63 | // 仅 ip 地址 64 | myip.GET("/myip", getMyIP) 65 | //json 结构化的 ip 地址 66 | myip.GET("/myip/format", getMyIPFormat) 67 | // 仅我的地理位置 68 | myip.GET("/mylocation", getMyLocation) 69 | //json 结构化的我的地理位置 70 | myip.GET("/mylocation/format", getMyLocationFormat) 71 | 72 | rest := r.Group("/api/v1") 73 | rest.Use(XAPICheckMidd) 74 | rest.GET("/network/ip", openGetIpApi) 75 | rest.DELETE("/ratelimit", clearRateLimit) 76 | rest.GET("/ratelimit", getRateLimit) 77 | 78 | // sso认证回调 79 | sso := r.Group("/sso") 80 | sso.Use(NoCache()) 81 | // logout 82 | sso.GET("/logout", ssoLogout) 83 | // oauth 84 | sso.GET("/callback/oauth2", OauthAuth) 85 | } 86 | 87 | func index(c *gin.Context) { 88 | if g.Config().SSO.Enabled { 89 | var username, nickname string 90 | session := sessions.Default(c) 91 | u := session.Get("username") 92 | n := session.Get("nickname") 93 | if u != nil { 94 | username = u.(string) 95 | } 96 | if n != nil { 97 | nickname = n.(string) 98 | } 99 | if g.Config().Oauth2.Enabled { 100 | authCodeURL := g.Oauth2Config.AuthCodeURL(util.RandStringRunes(16)) 101 | c.HTML(http.StatusOK, "index.html", gin.H{ 102 | "title": "主页", "sso": g.Config().SSO, "oauth2": g.Config().Oauth2, "authCodeURL": authCodeURL, "username": username, "nickname": nickname}) 103 | return 104 | } 105 | } 106 | c.HTML(http.StatusOK, "index.html", gin.H{ 107 | "title": "主页"}) 108 | } 109 | 110 | func CORS() gin.HandlerFunc { 111 | return func(context *gin.Context) { 112 | logger.Debug(context.Request.RequestURI, " - ", context.Request.Header.Get("Origin")) 113 | if util.InSliceStrFuzzy(context.Request.Header.Get("Origin"), g.Config().Http.CORS) { 114 | context.Writer.Header().Add("Access-Control-Allow-Origin", context.Request.Header.Get("Origin")) 115 | context.Writer.Header().Set("Access-Control-Max-Age", "86400") 116 | context.Writer.Header().Set("Access-Control-Allow-Methods", "GET") 117 | context.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, X-API-KEY, Authorization, x-requested-with") 118 | context.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length") 119 | context.Writer.Header().Set("Access-Control-Allow-Credentials", "true") 120 | context.Writer.Header().Set("Cache-Control", "no-cache") 121 | } 122 | if context.Request.Method == "OPTIONS" { 123 | context.AbortWithStatus(200) 124 | } else { 125 | context.Next() 126 | } 127 | } 128 | } 129 | 130 | func NoCache() gin.HandlerFunc { 131 | return func(context *gin.Context) { 132 | context.Writer.Header().Add("Cache-Control", "no-store") 133 | context.Writer.Header().Add("Pragma", "no-cache") 134 | context.Next() 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /cron/sync.go: -------------------------------------------------------------------------------- 1 | package cron 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/ECNU/open-geoip/g" 7 | "github.com/ECNU/open-geoip/util" 8 | "github.com/toolkits/pkg/logger" 9 | ) 10 | 11 | const ( 12 | DefaultInterval = 24 13 | ) 14 | 15 | func SyncMaxmindDatabase() { 16 | interval := g.Config().AutoDownload.Interval 17 | if interval == 0 { 18 | interval = DefaultInterval 19 | } 20 | t := time.NewTicker(time.Hour * time.Duration(interval)) 21 | defer t.Stop() 22 | 23 | for { 24 | _, err := util.AutoDownloadMaxmindDatabase(g.Config().AutoDownload) 25 | if err != nil { 26 | logger.Errorf("sync maxmind database failed %s", err) 27 | continue 28 | } 29 | logger.Debug("maxmind database sync successed") 30 | <-t.C 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /demo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ECNU/open-geoip/1eb64cd64c4856c5e2624e9d19b205c71073e350/demo.jpg -------------------------------------------------------------------------------- /g/cfg.go: -------------------------------------------------------------------------------- 1 | package g 2 | 3 | import ( 4 | "encoding/json" 5 | "log" 6 | "sync" 7 | 8 | "github.com/toolkits/file" 9 | ) 10 | 11 | /* 12 | GlobalConfig 全局配置 13 | */ 14 | type GlobalConfig struct { 15 | Logger LoggerSection `json:"logger"` 16 | Redis RedisConfig `json:"redis"` 17 | DB DBConfig `json:"db"` 18 | Campus CampusConfig `json:"campus"` 19 | InternalDB InternalDBConfig `json:"internaldb"` 20 | Source SourceConfig `json:"source"` 21 | AutoDownload AutoDownloadConfig `json:"autoDownload"` 22 | RateLimit RateLimitConfig `json:"rateLimit"` 23 | Http HttpConfig `json:"http"` 24 | SSO SSO `json:"sso"` 25 | Oauth2 OAuth2 `json:"oauth2"` 26 | } 27 | 28 | /* 29 | RedisConfig 全局配置 30 | */ 31 | type RedisConfig struct { 32 | Dsn string `json:"dsn"` 33 | MaxIdle int `json:"maxIdle"` 34 | ConnTimeout int `json:"connTimeout"` 35 | ReadTimeout int `json:"readTimeout"` 36 | WriteTimeout int `json:"writeTimeout"` 37 | Password string `json:"password"` 38 | } 39 | 40 | /* 41 | AutoDownloadConfig 自动下载的配置 42 | */ 43 | type AutoDownloadConfig struct { 44 | Enabled bool `json:"enabled"` 45 | MaxmindLicenseKey string `json:"maxmindLicenseKey"` 46 | TargetFilePath string `json:"targetFilePath"` 47 | Timeout int `json:"timeout"` 48 | Interval int `json:"interval"` 49 | } 50 | 51 | /* 52 | DBConfig DB 配置 53 | */ 54 | type DBConfig struct { 55 | Maxmind string `json:"maxmind"` 56 | Qqzengip string `json:"qqzengip"` 57 | Ipdb string `json:"ipdb"` 58 | } 59 | 60 | /* 61 | InternalDBConfi 内部数据库 62 | */ 63 | type InternalDBConfig struct { 64 | Source string `json:"source"` 65 | Auth bool `json:"auth"` 66 | Enabled bool `json:"enabled"` 67 | DB string `json:"db"` 68 | } 69 | 70 | /* 71 | RateLimitConfig 限流配置 72 | */ 73 | type RateLimitConfig struct { 74 | Enabled bool `json:"enabled"` 75 | Minute int `json:"minute"` 76 | Hour int `json:"hour"` 77 | Day int `json:"day"` 78 | } 79 | 80 | /* 81 | CampusConfig 园区内网配置 82 | */ 83 | type CampusConfig struct { 84 | Continent string `json:"continent"` //州 85 | Country string `json:"country"` //国家 86 | Province string `json:"province"` //省 87 | City string `json:"city"` //城市 88 | District string `json:"district"` //区县(行政区) 89 | ISP string `json:"isp"` //运营商 90 | AreaCode string `json:"areaCode"` //行政区划代码(国内) 91 | CountryEnglish string `json:"countryEnglish"` //国家英文名 92 | CountryCode string `json:"countryCode"` //国家英文代码 93 | Longitude string `json:"longitude"` //经度 94 | Latitude string `json:"latitude"` //纬度 95 | IPs []string `json:"ips"` 96 | } 97 | 98 | /* 99 | SourceConfig 数据源 100 | */ 101 | type SourceConfig struct { 102 | IPv4 string `json:"ipv4"` 103 | IPv6 string `json:"ipv6"` 104 | } 105 | 106 | /* 107 | HttpConfig Http 配置 108 | */ 109 | type HttpConfig struct { 110 | Listen string `json:"listen"` 111 | TrustProxy []string `json:"trustProxy"` 112 | XAPIKey string `json:"x-api-key"` 113 | CORS []string `json:"cors"` 114 | SessionOptions SessionOptionsConfig `json:"sessionOptions"` 115 | } 116 | 117 | /* 118 | SessionOptionsConfig Session 配置 119 | */ 120 | type SessionOptionsConfig struct { 121 | Path string `json:"path"` 122 | Domain string `json:"domain"` 123 | MaxAge int `json:"maxAge"` 124 | Secure bool `json:"secure"` 125 | HttpOnly bool `json:"httpOnly"` 126 | } 127 | 128 | // SSO 配置 129 | type SSO struct { 130 | Enabled bool `json:"enabled"` 131 | AuthExpire int `json:"authExpire"` 132 | Type string `json:"type"` 133 | } 134 | 135 | // OAuth2 配置 136 | type OAuth2 struct { 137 | Enabled bool `json:"enabled"` 138 | DisplayName string `json:"displayName"` 139 | RedirectURL string `json:"redirectURL"` 140 | AuthAddr string `json:"authAddr"` 141 | TokenAddr string `json:"tokenAddr"` 142 | UserInfoAddr string `json:"userInfoAddr"` 143 | LogoutAddr string `json:"logoutAddr"` 144 | ClientId string `json:"clientId"` 145 | ClientSecret string `json:"clientSecret"` 146 | UserinfoIsArray bool `json:"userinfoIsArray"` 147 | UserinfoPrefix string `json:"userinfoPrefix"` 148 | Scopes []string `json:"scopes"` 149 | Attributes OauthAttributes 150 | } 151 | 152 | type OauthAttributes struct { 153 | Username string `json:"userName"` 154 | Nickname string `json:"nickName"` 155 | } 156 | 157 | var ( 158 | ConfigFile string 159 | config *GlobalConfig 160 | lock = new(sync.RWMutex) 161 | ) 162 | 163 | /* 164 | Config 安全的读取和修改配置 165 | */ 166 | func Config() *GlobalConfig { 167 | lock.RLock() 168 | defer lock.RUnlock() 169 | return config 170 | } 171 | 172 | /* 173 | ParseConfig 加载配置 174 | */ 175 | func ParseConfig(cfg string) { 176 | if cfg == "" { 177 | log.Fatalln("use -c to specify configuration file") 178 | } 179 | 180 | if !file.IsExist(cfg) { 181 | log.Fatalln("config file:", cfg, "is not existent. maybe you need `mv cfg.example.json cfg.json`") 182 | } 183 | 184 | ConfigFile = cfg 185 | 186 | configContent, err := file.ToTrimString(cfg) 187 | if err != nil { 188 | log.Fatalln("read config file:", cfg, "fail:", err) 189 | } 190 | 191 | var c GlobalConfig 192 | err = json.Unmarshal([]byte(configContent), &c) 193 | if err != nil { 194 | log.Fatalln("parse config file:", cfg, "fail:", err) 195 | } 196 | 197 | lock.Lock() 198 | defer lock.Unlock() 199 | 200 | config = &c 201 | } 202 | -------------------------------------------------------------------------------- /g/const.go: -------------------------------------------------------------------------------- 1 | package g 2 | 3 | const ( 4 | VERSION = "0.4.0" 5 | ) 6 | -------------------------------------------------------------------------------- /g/load.go: -------------------------------------------------------------------------------- 1 | package g 2 | 3 | import ( 4 | "github.com/gocarina/gocsv" 5 | "github.com/maxmind/mmdbwriter" 6 | "github.com/maxmind/mmdbwriter/inserter" 7 | "github.com/maxmind/mmdbwriter/mmdbtype" 8 | "github.com/toolkits/file" 9 | "log" 10 | "net" 11 | "os" 12 | ) 13 | 14 | type Ips struct { 15 | IPSubnet string `csv:"ip_subnet"` //IP地址 16 | Continent string `csv:"continent"` //州 17 | Country string `csv:"country"` //国家 18 | Province string `csv:"province"` //省 19 | City string `csv:"city"` //城市 20 | District string `csv:"district"` //区县(行政区) 21 | ISP string `csv:"isp"` //运营商 22 | AreaCode string `csv:"areaCode"` //行政区划代码(国内) 23 | CountryEnglish string `csv:"countryEnglish"` //国家英文名 24 | CountryCode string `csv:"countryCode"` //国家英文代码 25 | Longitude string `csv:"longitude"` //经度 26 | Latitude string `csv:"latitude"` //纬度 27 | } 28 | 29 | func InitInternalDB(csvFile string) { 30 | 31 | if !file.IsExist(csvFile) { 32 | log.Fatalln("config file:", csvFile, "is not existent. maybe you need `mv cfg.example.json cfg.json`") 33 | } 34 | 35 | ips, err := loadDBFIle(csvFile) 36 | if err != nil { 37 | log.Println("cannot init internal db:", err) 38 | os.Exit(1) 39 | } 40 | 41 | err = saveMMDB(ips) 42 | if err != nil { 43 | log.Println("cannot init internal db:", err) 44 | os.Exit(1) 45 | } 46 | 47 | } 48 | 49 | func loadDBFIle(csvFile string) (ips []*Ips, err error) { 50 | 51 | DBFile, err := os.OpenFile(csvFile, os.O_RDWR|os.O_CREATE, os.ModePerm) 52 | if err != nil { 53 | return 54 | } 55 | defer DBFile.Close() 56 | 57 | err = gocsv.UnmarshalFile(DBFile, &ips) 58 | 59 | if err != nil { 60 | return 61 | } 62 | 63 | return 64 | } 65 | 66 | func saveMMDB(ips []*Ips) (err error) { 67 | 68 | writer, err := mmdbwriter.New(mmdbwriter.Options{DatabaseType: "GeoIP2-City", IncludeReservedNetworks: true}) 69 | 70 | if err != nil { 71 | return 72 | } 73 | 74 | for _, ip := range ips { 75 | 76 | _, sreNet, err := net.ParseCIDR(ip.IPSubnet) 77 | 78 | if err != nil { 79 | return err 80 | } 81 | 82 | sreData := mmdbtype.Map{ 83 | "subdivisions": mmdbtype.Slice{ 84 | mmdbtype.Map{ 85 | "names": mmdbtype.Map{ 86 | "zh-CN": mmdbtype.String(ip.Province), 87 | }, 88 | }, 89 | }, 90 | "city": mmdbtype.Map{ 91 | //"code": mmdbtype.String("AS"), 92 | //"geoname_id": mmdbtype.Uint64(1808926), 93 | "names": mmdbtype.Map{ 94 | //"de": mmdbtype.String("China"), 95 | //"en": mmdbtype.String("China"), 96 | //"es": mmdbtype.String("China"), 97 | //"fr": mmdbtype.String("Chine"), 98 | //"ja": mmdbtype.String("中国"), 99 | //"pt-BR": mmdbtype.String("China"), 100 | //"ru": mmdbtype.String("Китай"), 101 | "zh-CN": mmdbtype.String(ip.City), 102 | }, 103 | }, 104 | "continent": mmdbtype.Map{ 105 | "names": mmdbtype.Map{ 106 | "zh-CN": mmdbtype.String(ip.Continent), 107 | }, 108 | }, 109 | "country": mmdbtype.Map{ 110 | "names": mmdbtype.Map{ 111 | "zh-CN": mmdbtype.String(ip.Country), 112 | "en": mmdbtype.String(ip.CountryEnglish), 113 | }, 114 | "iso_code": mmdbtype.String(ip.CountryCode), 115 | }, 116 | "registered_country": mmdbtype.Map{ 117 | "names": mmdbtype.Map{ 118 | "zh-CN": mmdbtype.String(ip.Country), 119 | }, 120 | }, 121 | "internal": mmdbtype.Map{ 122 | "isp": mmdbtype.Map{ 123 | "zh-CN": mmdbtype.String(ip.ISP), 124 | }, 125 | "district": mmdbtype.Map{ 126 | "zh-CN": mmdbtype.String(ip.District), 127 | }, 128 | "areaCode": mmdbtype.String(ip.AreaCode), 129 | }, 130 | } 131 | 132 | if err := writer.InsertFunc(sreNet, inserter.TopLevelMergeWith(sreData)); err != nil { 133 | return err 134 | } 135 | 136 | } 137 | 138 | // 139 | fh, err := os.Create("internal.mmdb") 140 | if err != nil { 141 | return 142 | } 143 | 144 | _, err = writer.WriteTo(fh) 145 | if err != nil { 146 | return 147 | } 148 | return 149 | } 150 | -------------------------------------------------------------------------------- /g/logger.go: -------------------------------------------------------------------------------- 1 | package g 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/toolkits/pkg/logger" 8 | ) 9 | 10 | type LoggerSection struct { 11 | Dir string `json:"dir"` 12 | Level string `json:"level"` 13 | KeepHours uint `json:"keepHours"` 14 | } 15 | 16 | func InitLog(l LoggerSection) { 17 | 18 | lb, err := logger.NewFileBackend(l.Dir) 19 | if err != nil { 20 | fmt.Println("cannot init logger:", err) 21 | os.Exit(1) 22 | } 23 | lb.SetRotateByHour(true) 24 | lb.SetKeepHours(l.KeepHours) 25 | 26 | logger.SetLogging(l.Level, lb) 27 | } 28 | -------------------------------------------------------------------------------- /g/oauth2.go: -------------------------------------------------------------------------------- 1 | package g 2 | 3 | import ( 4 | "fmt" 5 | 6 | "golang.org/x/oauth2" 7 | ) 8 | 9 | var Oauth2Config *oauth2.Config 10 | 11 | func InitOauth2() { 12 | fmt.Printf("2222%v\n\n", Config().Oauth2.ClientId) 13 | Oauth2Config = &oauth2.Config{ 14 | ClientID: Config().Oauth2.ClientId, 15 | ClientSecret: Config().Oauth2.ClientSecret, 16 | RedirectURL: Config().Oauth2.RedirectURL, 17 | Scopes: Config().Oauth2.Scopes, 18 | Endpoint: oauth2.Endpoint{ 19 | AuthURL: Config().Oauth2.AuthAddr, 20 | TokenURL: Config().Oauth2.TokenAddr, 21 | }, 22 | } 23 | } 24 | 25 | // 26 | //http.HandleFunc("/", handleMain) 27 | //http.HandleFunc("/login", handleLogin) 28 | //http.HandleFunc("/callback", handleCallback) 29 | // 30 | //log.Println("Server started on http://localhost:8080") 31 | //log.Fatal(http.ListenAndServe(":8080", nil)) 32 | -------------------------------------------------------------------------------- /g/redis.go: -------------------------------------------------------------------------------- 1 | package g 2 | 3 | import ( 4 | "log" 5 | "time" 6 | 7 | "github.com/gomodule/redigo/redis" 8 | ) 9 | 10 | var redisConnPool *redis.Pool 11 | 12 | func ConnectRedis() *redis.Pool { 13 | return redisConnPool 14 | } 15 | 16 | func CloseRedis() (err error) { 17 | err = redisConnPool.Close() 18 | return 19 | } 20 | 21 | func InitRedisConnPool() { 22 | dsn := Config().Redis.Dsn 23 | maxIdle := Config().Redis.MaxIdle 24 | idleTimeout := 240 * time.Second 25 | connTimeout := time.Duration(Config().Redis.ConnTimeout) * time.Second 26 | readTimeout := time.Duration(Config().Redis.ReadTimeout) * time.Second 27 | writeTimeout := time.Duration(Config().Redis.WriteTimeout) * time.Second 28 | password := Config().Redis.Password 29 | 30 | redisConnPool = &redis.Pool{ 31 | MaxIdle: maxIdle, 32 | IdleTimeout: idleTimeout, 33 | Dial: func() (redis.Conn, error) { 34 | c, err := redis.Dial("tcp", dsn, 35 | redis.DialConnectTimeout(connTimeout), 36 | redis.DialReadTimeout(readTimeout), 37 | redis.DialWriteTimeout(writeTimeout), 38 | redis.DialPassword(password)) 39 | if err != nil { 40 | return nil, err 41 | } 42 | return c, err 43 | }, 44 | TestOnBorrow: pingRedis, 45 | } 46 | } 47 | 48 | func pingRedis(c redis.Conn, t time.Time) error { 49 | _, err := c.Do("ping") 50 | if err != nil { 51 | log.Println("[ERROR] ping redis fail", err) 52 | } 53 | return err 54 | } 55 | -------------------------------------------------------------------------------- /geoip_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | "net/http/httptest" 8 | "testing" 9 | 10 | "github.com/ECNU/open-geoip/controller" 11 | "github.com/stretchr/testify/assert" 12 | 13 | "github.com/ECNU/open-geoip/g" 14 | "github.com/ECNU/open-geoip/models" 15 | ) 16 | 17 | func init() { 18 | g.InitInternalDB("internal.csv") 19 | g.ParseConfig("cfg.json.test") 20 | g.InitRedisConnPool() 21 | err := models.InitReader() 22 | if err != nil { 23 | log.Fatalf("load geo db failed, %v", err) 24 | } 25 | 26 | } 27 | 28 | func TestInternalDB(t *testing.T) { 29 | g.Config().InternalDB.Enabled = true 30 | err := models.InitReader() 31 | if err != nil { 32 | log.Fatalf("load geo db failed, %v", err) 33 | } 34 | httpServer := controller.InitGin(":8080") 35 | // 创建一个测试请求 36 | req, err := http.NewRequest("GET", "/ip?ip=192.168.0.1", nil) 37 | if err != nil { 38 | t.Fatal(err) 39 | } 40 | // 创建一个响应记录器 41 | w := httptest.NewRecorder() 42 | // 调用测试服务器的处理函数 43 | httpServer.Handler.ServeHTTP(w, req) 44 | // 检查响应状态码是否为 200 45 | assert.Equal(t, 200, w.Code) 46 | // 检查响应内容是否包含 IP 地址 47 | assert.Contains(t, w.Body.String(), "中国") 48 | 49 | req, err = http.NewRequest("GET", "/ip?ip=fd12:3456:789a:bcde::1", nil) 50 | if err != nil { 51 | t.Fatal(err) 52 | } 53 | // 创建一个响应记录器 54 | w = httptest.NewRecorder() 55 | // 调用测试服务器的处理函数 56 | httpServer.Handler.ServeHTTP(w, req) 57 | // 检查响应状态码是否为 200 58 | assert.Equal(t, 200, w.Code) 59 | // 检查响应内容是否包含 IP 地址 60 | assert.Contains(t, w.Body.String(), "中国") 61 | 62 | req, err = http.NewRequest("GET", "/ip?ip=223.5.5.5", nil) 63 | if err != nil { 64 | t.Fatal(err) 65 | } 66 | // 创建一个响应记录器 67 | w = httptest.NewRecorder() 68 | // 调用测试服务器的处理函数 69 | httpServer.Handler.ServeHTTP(w, req) 70 | // 检查响应状态码是否为 200 71 | assert.Equal(t, 200, w.Code) 72 | // 检查响应内容是否包含 IP 地址 73 | fmt.Printf("%v\n", w.Body.String()) 74 | assert.Contains(t, w.Body.String(), "ALIDNS") 75 | //测完了关闭,不干扰其他测试用例 76 | g.Config().InternalDB.Enabled = false 77 | } 78 | 79 | func TestIndex(t *testing.T) { 80 | // 创建一个测试服务器 81 | httpServer := controller.InitGin(":8080") 82 | // 创建一个测试请求 83 | req, err := http.NewRequest("GET", "/", nil) 84 | if err != nil { 85 | t.Fatal(err) 86 | } 87 | // 创建一个响应记录器 88 | w := httptest.NewRecorder() 89 | // 调用测试服务器的处理函数 90 | httpServer.Handler.ServeHTTP(w, req) 91 | // 检查响应状态码是否为 200 92 | assert.Equal(t, 200, w.Code) 93 | // 检查响应内容是否包含 open-geoip 地址 94 | assert.Contains(t, w.Body.String(), "open-geoip") 95 | } 96 | 97 | func TestSeachAPI(t *testing.T) { 98 | // 创建一个测试服务器 99 | httpServer := controller.InitGin(":8080") 100 | // 创建一个测试请求 101 | req, err := http.NewRequest("GET", "/ip?ip=202.120.92.60", nil) 102 | if err != nil { 103 | t.Fatal(err) 104 | } 105 | // 创建一个响应记录器 106 | w := httptest.NewRecorder() 107 | // 调用测试服务器的处理函数 108 | httpServer.Handler.ServeHTTP(w, req) 109 | // 检查响应状态码是否为 200 110 | assert.Equal(t, 200, w.Code) 111 | // 检查响应内容是否包含 IP 地址 112 | assert.Contains(t, w.Body.String(), "中国") 113 | } 114 | 115 | func TestOpenAPI(t *testing.T) { 116 | // 创建一个测试服务器 117 | httpServer := controller.InitGin(":8080") 118 | // 创建一个测试请求,带有 X-API-KEY 头 119 | req, err := http.NewRequest("GET", "/api/v1/network/ip?ip=202.120.92.60", nil) 120 | if err != nil { 121 | t.Fatal(err) 122 | } 123 | req.Header.Set("X-API-KEY", "this-is-key") 124 | // 创建一个响应记录器 125 | w := httptest.NewRecorder() 126 | 127 | // 调用测试服务器的处理函数 128 | httpServer.Handler.ServeHTTP(w, req) 129 | // 检查响应状态码是否为 200 130 | assert.Equal(t, 200, w.Code) 131 | // 检查响应内容是否包含 IP 地址 132 | assert.Contains(t, w.Body.String(), "中国") 133 | } 134 | 135 | func BenchmarkIndex(b *testing.B) { 136 | // 创建一个测试服务器 137 | httpServer := controller.InitGin(":8080") 138 | // 重置计时器 139 | b.ResetTimer() 140 | // 循环执行 b.N 次测试 141 | for i := 0; i < b.N; i++ { 142 | // 创建一个测试请求 143 | req, err := http.NewRequest("GET", "/", nil) 144 | if err != nil { 145 | b.Fatal(err) 146 | } 147 | // 创建一个响应记录器 148 | w := httptest.NewRecorder() 149 | // 调用测试服务器的处理函数 150 | httpServer.Handler.ServeHTTP(w, req) 151 | } 152 | } 153 | 154 | func BenchmarkSeachAPIForIPv4(b *testing.B) { 155 | // 创建一个测试服务器 156 | httpServer := controller.InitGin(":8080") 157 | // 重置计时器 158 | b.ResetTimer() 159 | // 循环执行 b.N 次测试 160 | for i := 0; i < b.N; i++ { 161 | // 创建一个测试请求 162 | req, err := http.NewRequest("GET", "/ip?202.120.92.60", nil) 163 | if err != nil { 164 | b.Fatal(err) 165 | } 166 | // 创建一个响应记录器 167 | w := httptest.NewRecorder() 168 | // 调用测试服务器的处理函数 169 | httpServer.Handler.ServeHTTP(w, req) 170 | } 171 | } 172 | 173 | func BenchmarkSeachAPIForIPv6(b *testing.B) { 174 | // 创建一个测试服务器 175 | httpServer := controller.InitGin(":8080") 176 | // 重置计时器 177 | b.ResetTimer() 178 | // 循环执行 b.N 次测试 179 | for i := 0; i < b.N; i++ { 180 | // 创建一个测试请求 181 | req, err := http.NewRequest("GET", "/ip?2001:da8:8005::1", nil) 182 | if err != nil { 183 | b.Fatal(err) 184 | } 185 | // 创建一个响应记录器 186 | w := httptest.NewRecorder() 187 | // 调用测试服务器的处理函数 188 | httpServer.Handler.ServeHTTP(w, req) 189 | } 190 | } 191 | 192 | func BenchmarkOpenAPIForIPv4(b *testing.B) { 193 | // 创建一个测试服务器 194 | httpServer := controller.InitGin(":8080") 195 | // 重置计时器 196 | b.ResetTimer() 197 | // 循环执行 b.N 次测试 198 | for i := 0; i < b.N; i++ { 199 | // 创建一个测试请求 200 | req, err := http.NewRequest("GET", "/api/v1/network/ip?202.120.92.60", nil) 201 | if err != nil { 202 | b.Fatal(err) 203 | } 204 | req.Header.Set("X-API-KEY", "this-is-key") 205 | // 创建一个响应记录器 206 | w := httptest.NewRecorder() 207 | // 调用测试服务器的处理函数 208 | httpServer.Handler.ServeHTTP(w, req) 209 | } 210 | } 211 | 212 | func BenchmarkOpenAPIForIPv6(b *testing.B) { 213 | // 创建一个测试服务器 214 | httpServer := controller.InitGin(":8080") 215 | // 重置计时器 216 | b.ResetTimer() 217 | // 循环执行 b.N 次测试 218 | for i := 0; i < b.N; i++ { 219 | // 创建一个测试请求 220 | req, err := http.NewRequest("GET", "/api/v1/network/ip?2001:da8:8005::1", nil) 221 | if err != nil { 222 | b.Fatal(err) 223 | } 224 | req.Header.Set("X-API-KEY", "this-is-key") 225 | // 创建一个响应记录器 226 | w := httptest.NewRecorder() 227 | // 调用测试服务器的处理函数 228 | httpServer.Handler.ServeHTTP(w, req) 229 | } 230 | } 231 | -------------------------------------------------------------------------------- /gitversion: -------------------------------------------------------------------------------- 1 | 7545930 2 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/ECNU/open-geoip 2 | 3 | go 1.19 4 | 5 | require ( 6 | github.com/alicebob/miniredis/v2 v2.30.2 7 | github.com/gin-contrib/sessions v0.0.5 8 | github.com/gin-gonic/gin v1.9.1 9 | github.com/gocarina/gocsv v0.0.0-20230406101422-6445c2b15027 10 | github.com/gomodule/redigo v2.0.0+incompatible 11 | github.com/ipipdotnet/ipdb-go v1.3.3 12 | github.com/json-iterator/go v1.1.12 13 | github.com/maxmind/mmdbwriter v0.0.0-20230320152106-28b0f681af62 14 | github.com/oschwald/geoip2-golang v1.8.0 15 | github.com/oschwald/maxminddb-golang v1.10.0 16 | github.com/pieterclaerhout/go-geoip/v2 v2.0.7 17 | github.com/satori/go.uuid v1.2.0 18 | github.com/stretchr/testify v1.8.3 19 | github.com/toolkits/file v0.0.0-20160325033739-a5b3c5147e07 20 | github.com/toolkits/pkg v1.3.3 21 | golang.org/x/oauth2 v0.10.0 22 | ) 23 | 24 | require ( 25 | github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a // indirect 26 | github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff // indirect 27 | github.com/bytedance/sonic v1.9.1 // indirect 28 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect 29 | github.com/davecgh/go-spew v1.1.1 // indirect 30 | github.com/gabriel-vasile/mimetype v1.4.2 // indirect 31 | github.com/gin-contrib/sse v0.1.0 // indirect 32 | github.com/go-playground/locales v0.14.1 // indirect 33 | github.com/go-playground/universal-translator v0.18.1 // indirect 34 | github.com/go-playground/validator/v10 v10.14.0 // indirect 35 | github.com/goccy/go-json v0.10.2 // indirect 36 | github.com/golang/protobuf v1.5.3 // indirect 37 | github.com/gorilla/context v1.1.1 // indirect 38 | github.com/gorilla/securecookie v1.1.1 // indirect 39 | github.com/gorilla/sessions v1.2.1 // indirect 40 | github.com/klauspost/cpuid/v2 v2.2.4 // indirect 41 | github.com/leodido/go-urn v1.2.4 // indirect 42 | github.com/mattn/go-isatty v0.0.19 // indirect 43 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 44 | github.com/modern-go/reflect2 v1.0.2 // indirect 45 | github.com/pelletier/go-toml/v2 v2.0.8 // indirect 46 | github.com/pkg/errors v0.9.1 // indirect 47 | github.com/pmezard/go-difflib v1.0.0 // indirect 48 | github.com/twitchyliquid64/golang-asm v0.15.1 // indirect 49 | github.com/ugorji/go/codec v1.2.11 // indirect 50 | github.com/yuin/gopher-lua v1.1.0 // indirect 51 | go4.org/netipx v0.0.0-20220812043211-3cc044ffd68d // indirect 52 | golang.org/x/arch v0.3.0 // indirect 53 | golang.org/x/crypto v0.11.0 // indirect 54 | golang.org/x/net v0.12.0 // indirect 55 | golang.org/x/sys v0.10.0 // indirect 56 | golang.org/x/text v0.11.0 // indirect 57 | google.golang.org/appengine v1.6.7 // indirect 58 | google.golang.org/protobuf v1.31.0 // indirect 59 | gopkg.in/yaml.v3 v3.0.1 // indirect 60 | ) 61 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 2 | github.com/Flaque/filet v0.0.0-20190209224823-fc4d33cfcf93 h1:NnAUCP75PRm8yWE7+MZBIAR6PA9iwsBYEc6ZNYOy+AQ= 3 | github.com/Flaque/filet v0.0.0-20190209224823-fc4d33cfcf93/go.mod h1:TK+jB3mBs+8ZMWhU5BqZKnZWJ1MrLo8etNVg51ueTBo= 4 | github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a h1:HbKu58rmZpUGpz5+4FfNmIU+FmZg2P3Xaj2v2bfNWmk= 5 | github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= 6 | github.com/alicebob/miniredis/v2 v2.30.2 h1:lc1UAUT9ZA7h4srlfBmBt2aorm5Yftk9nBjxz7EyY9I= 7 | github.com/alicebob/miniredis/v2 v2.30.2/go.mod h1:b25qWj4fCEsBeAAR2mlb0ufImGC6uH3VlUfb/HS5zKg= 8 | github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff h1:RmdPFa+slIr4SCBg4st/l/vZWVe9QJKMXGO60Bxbe04= 9 | github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff/go.mod h1:+RTT1BOk5P97fT2CiHkbFQwkK3mjsFAP6zCYV2aXtjw= 10 | github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= 11 | github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s= 12 | github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= 13 | github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= 14 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= 15 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= 16 | github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= 17 | github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= 18 | github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= 19 | github.com/davecgh/go-spew v0.0.0-20161028175848-04cdfd42973b/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 20 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 21 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 22 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 23 | github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= 24 | github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= 25 | github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= 26 | github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= 27 | github.com/garyburd/redigo v1.6.2/go.mod h1:NR3MbYisc3/PwhQ00EMzDiPmrwpPxAn5GI05/YaO1SY= 28 | github.com/gin-contrib/sessions v0.0.5 h1:CATtfHmLMQrMNpJRgzjWXD7worTh7g7ritsQfmF+0jE= 29 | github.com/gin-contrib/sessions v0.0.5/go.mod h1:vYAuaUPqie3WUSsft6HUlCjlwwoJQs97miaG2+7neKY= 30 | github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= 31 | github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= 32 | github.com/gin-gonic/gin v1.7.7/go.mod h1:axIBovoeJpVj8S3BwE0uPMTeReE4+AfFtqpqaZ1qq1U= 33 | github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= 34 | github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= 35 | github.com/go-chi/chi v4.1.1+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ= 36 | github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= 37 | github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= 38 | github.com/go-playground/form/v4 v4.1.1/go.mod h1:q1a2BY+AQUUzhl6xA/6hBetay6dEIhMHjgvJiGo6K7U= 39 | github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= 40 | github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= 41 | github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= 42 | github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= 43 | github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= 44 | github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= 45 | github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= 46 | github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js= 47 | github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= 48 | github.com/gocarina/gocsv v0.0.0-20230406101422-6445c2b15027 h1:LCGzZb4kMUUjMUzLxxqSJBwo9szUO0tK8cOxnEOT4Jc= 49 | github.com/gocarina/gocsv v0.0.0-20230406101422-6445c2b15027/go.mod h1:5YoVOkjYAQumqlV356Hj3xeYh4BdZuLE0/nRkf2NKkI= 50 | github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= 51 | github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= 52 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 53 | github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= 54 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= 55 | github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= 56 | github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= 57 | github.com/gomodule/redigo v2.0.0+incompatible h1:K/R+8tc58AaqLkqG2Ol3Qk+DR/TlNuhuh457pBFPtt0= 58 | github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= 59 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 60 | github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= 61 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 62 | github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= 63 | github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8= 64 | github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= 65 | github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= 66 | github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= 67 | github.com/gorilla/sessions v1.1.1/go.mod h1:8KCfur6+4Mqcc6S0FEfKuN15Vl5MgXW92AE8ovaJD0w= 68 | github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI= 69 | github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= 70 | github.com/ipipdotnet/ipdb-go v1.3.3 h1:GLSAW9ypLUd6EF9QNK2Uhxew9Jzs4XMJ9gOZEFnJm7U= 71 | github.com/ipipdotnet/ipdb-go v1.3.3/go.mod h1:yZ+8puwe3R37a/3qRftXo40nZVQbxYDLqls9o5foexs= 72 | github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc= 73 | github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= 74 | github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= 75 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= 76 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= 77 | github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= 78 | github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= 79 | github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= 80 | github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= 81 | github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= 82 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 83 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 84 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= 85 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 86 | github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= 87 | github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= 88 | github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= 89 | github.com/markusthoemmes/goautoneg v0.0.0-20190713162725-c6008fefa5b1/go.mod h1:qFhy2RoC9EWZC7fgczcBbUpzGNFfIm5//VO/gde0AbI= 90 | github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= 91 | github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= 92 | github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= 93 | github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= 94 | github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= 95 | github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 96 | github.com/maxmind/mmdbwriter v0.0.0-20230320152106-28b0f681af62 h1:Bc7ZYEQ3o04WkCGF5pNG4w6sKZpss7ggUplkXiRtb98= 97 | github.com/maxmind/mmdbwriter v0.0.0-20230320152106-28b0f681af62/go.mod h1:OTBr647IJpdisFRbIxLiEFMVL/lcPrmwxsvEIa/RQ9k= 98 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 99 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= 100 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 101 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 102 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= 103 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= 104 | github.com/oschwald/geoip2-golang v1.8.0 h1:KfjYB8ojCEn/QLqsDU0AzrJ3R5Qa9vFlx3z6SLNcKTs= 105 | github.com/oschwald/geoip2-golang v1.8.0/go.mod h1:R7bRvYjOeaoenAp9sKRS8GX5bJWcZ0laWO5+DauEktw= 106 | github.com/oschwald/maxminddb-golang v1.6.0/go.mod h1:DUJFucBg2cvqx42YmDa/+xHvb0elJtOm3o4aFQ/nb/w= 107 | github.com/oschwald/maxminddb-golang v1.10.0 h1:Xp1u0ZhqkSuopaKmk1WwHtjF0H9Hd9181uj2MQ5Vndg= 108 | github.com/oschwald/maxminddb-golang v1.10.0/go.mod h1:Y2ELenReaLAZ0b400URyGwvYxHV1dLIxBuyOsyYjHK0= 109 | github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ= 110 | github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4= 111 | github.com/pieterclaerhout/go-formatter v1.0.4/go.mod h1:1okQQFUwXCLGTWXoWoh3OGchp3i7KeebwIx/ufmsjks= 112 | github.com/pieterclaerhout/go-geoip/v2 v2.0.7 h1:ZgLbKIwFDQx+m6WuhhqfpYxOdRWU2QjrZTB0SKAlNvE= 113 | github.com/pieterclaerhout/go-geoip/v2 v2.0.7/go.mod h1:h9vtDlyaUgeZ7bLG/5VMdk4tGRXKWZYi7XxHjjphqJw= 114 | github.com/pieterclaerhout/go-log v1.14.0/go.mod h1:Zwdhg00fN6IuEWDvktUpu/XFMC5Y+NWrXyQ1RQHRPjc= 115 | github.com/pieterclaerhout/go-webserver/v2 v2.0.3/go.mod h1:lvYt/vW838Slf62NWLOECTWBaUiWCugRsxCKmb9A5Qs= 116 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 117 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= 118 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 119 | github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 120 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 121 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 122 | github.com/robfig/go-cache v0.0.0-20130306151617-9fc39e0dbf62/go.mod h1:65XQgovT59RWatovFwnwocoUxiI/eENTnOY5GK3STuY= 123 | github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= 124 | github.com/rotisserie/eris v0.4.0/go.mod h1:lODN/gtqebxPHRbCcWeCYOE350FC2M3V/oAPT2wKxAU= 125 | github.com/sanity-io/litter v1.2.0/go.mod h1:JF6pZUFgu2Q0sBZ+HSV35P8TVPI1TTzEwyu9FXAw2W4= 126 | github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= 127 | github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= 128 | github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= 129 | github.com/spf13/afero v1.2.2 h1:5jhuqJyZCZf2JRofRvN/nIFgIWNzPa3/Vz8mYylgbWc= 130 | github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= 131 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 132 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 133 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 134 | github.com/stretchr/testify v0.0.0-20161117074351-18a02ba4a312/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 135 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 136 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 137 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 138 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 139 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 140 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 141 | github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 142 | github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY= 143 | github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 144 | github.com/tidwall/gjson v1.3.2/go.mod h1:P256ACg0Mn+j1RXIDXoss50DeIABTYK1PULOJHhxOls= 145 | github.com/tidwall/match v1.0.1/go.mod h1:LujAq0jyVjBy028G1WhWfIzbpQfMO8bBZ6Tyb0+pL9E= 146 | github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= 147 | github.com/toolkits/file v0.0.0-20160325033739-a5b3c5147e07 h1:d/VUIMNTk65Xz69htmRPNfjypq2uNRqVsymcXQu6kKk= 148 | github.com/toolkits/file v0.0.0-20160325033739-a5b3c5147e07/go.mod h1:FbXpUxsx5in7z/OrWFDdhYetOy3/VGIJsVHN9G7RUPA= 149 | github.com/toolkits/pkg v1.3.3 h1:qpQAQ18Jr47dv4NcBALlH0ad7L2PuqSh5K+nJKNg5lU= 150 | github.com/toolkits/pkg v1.3.3/go.mod h1:USXArTJlz1f1DCnQHNPYugO8GPkr1NRhP4eYQZQVshk= 151 | github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= 152 | github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= 153 | github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= 154 | github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= 155 | github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU= 156 | github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= 157 | github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= 158 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 159 | github.com/yuin/gopher-lua v1.1.0 h1:BojcDhfyDWgU2f2TOzYK/g5p2gxMrku8oupLDqlnSqE= 160 | github.com/yuin/gopher-lua v1.1.0/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= 161 | go.uber.org/automaxprocs v1.4.0/go.mod h1:/mTEdr7LvHhs0v7mjdxDreTz1OG5zdZGqgOnhWiR/+Q= 162 | go4.org/netipx v0.0.0-20220812043211-3cc044ffd68d h1:ggxwEf5eu0l8v+87VhX1czFh8zJul3hK16Gmruxn7hw= 163 | go4.org/netipx v0.0.0-20220812043211-3cc044ffd68d/go.mod h1:tgPU4N2u9RByaTN3NC2p9xOzyFpte4jYwsIIRF7XlSc= 164 | golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= 165 | golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k= 166 | golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= 167 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 168 | golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 169 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 170 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 171 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= 172 | golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA= 173 | golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= 174 | golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= 175 | golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= 176 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= 177 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 178 | golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= 179 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 180 | golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 181 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 182 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= 183 | golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50= 184 | golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= 185 | golang.org/x/oauth2 v0.10.0 h1:zHCpF2Khkwy4mMB4bv0U37YtJdTGW8jI0glAApi0Kh8= 186 | golang.org/x/oauth2 v0.10.0/go.mod h1:kTpgurOux7LqtuxjuyZa4Gj2gdezIt/jQtGnNFfypQI= 187 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 188 | golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 189 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 190 | golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 191 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 192 | golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 193 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 194 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 195 | golang.org/x/sys v0.0.0-20191224085550-c709ea063b76/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 196 | golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 197 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 198 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 199 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 200 | golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 201 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 202 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 203 | golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= 204 | golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 205 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 206 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 207 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 208 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 209 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 210 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 211 | golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= 212 | golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= 213 | golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= 214 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 215 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 216 | golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 217 | golang.org/x/tools v0.0.0-20200522201501-cb1345f3a375/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= 218 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= 219 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 220 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 221 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 222 | google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= 223 | google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= 224 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= 225 | google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= 226 | google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= 227 | google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= 228 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 229 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= 230 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 231 | gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= 232 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 233 | gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 234 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 235 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 236 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 237 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 238 | honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= 239 | rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= 240 | -------------------------------------------------------------------------------- /internal.csv: -------------------------------------------------------------------------------- 1 | continent,country,province,city,district,isp,areaCode,countryCode,countryEnglish,longitude,latitude,ip_subnet 2 | ,,,,保留,回环地址,,,,,,127.0.0.0/8 3 | 亚洲,中国,上海,上海,开源教育,企业内网,310000,CN,China,,,10.0.0.0/8 4 | 亚洲,中国,上海,上海,开源教育,企业内网,310000,CN,China,,,192.168.0.0/16 5 | 亚洲,中国,上海,上海,开源教育,企业内网,310000,CN,China,,,172.16.0.0/12 6 | 亚洲,中国,上海,上海,开源教育,企业内网,310000,CN,China,,,fd00::/8 -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "flag" 6 | "fmt" 7 | "log" 8 | "net/http" 9 | "os" 10 | "os/signal" 11 | "syscall" 12 | "time" 13 | 14 | "github.com/ECNU/open-geoip/controller" 15 | "github.com/ECNU/open-geoip/cron" 16 | "github.com/ECNU/open-geoip/g" 17 | "github.com/ECNU/open-geoip/models" 18 | ) 19 | 20 | func main() { 21 | cfg := flag.String("c", "cfg.json", "configuration file") 22 | version := flag.Bool("v", false, "show version") 23 | csvFile := flag.String("csv", "", "internal file") 24 | flag.Parse() 25 | 26 | if *version { 27 | fmt.Println(g.VERSION) 28 | os.Exit(0) 29 | } 30 | 31 | if *csvFile != "" { 32 | fmt.Println("import csv file", *csvFile) 33 | g.InitInternalDB(*csvFile) 34 | os.Exit(0) 35 | } 36 | 37 | g.ParseConfig(*cfg) 38 | // init redis pool only ratelimit enbaled 39 | if g.Config().RateLimit.Enabled { 40 | g.InitRedisConnPool() 41 | } 42 | 43 | if g.Config().SSO.Enabled { 44 | if g.Config().Oauth2.Enabled { 45 | g.InitOauth2() 46 | } 47 | } 48 | 49 | srv := controller.InitGin(g.Config().Http.Listen) 50 | g.InitLog(g.Config().Logger) 51 | 52 | err := models.InitReader() 53 | if err != nil { 54 | log.Fatalf("load geo db failed, %v", err) 55 | } 56 | 57 | go func() { 58 | // service connections 59 | if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { 60 | log.Fatalf("listen: %s", err) 61 | } 62 | }() 63 | 64 | if g.Config().AutoDownload.Enabled { 65 | go cron.SyncMaxmindDatabase() 66 | } 67 | 68 | quit := make(chan os.Signal, 1) 69 | signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) 70 | <-quit 71 | log.Println("Shutdown Server ...") 72 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 73 | defer cancel() 74 | if err := srv.Shutdown(ctx); err != nil { 75 | log.Fatalf("Server Shutdown: %v", err) 76 | } 77 | log.Println("Server exit") 78 | } 79 | -------------------------------------------------------------------------------- /models/cfg.json.test: -------------------------------------------------------------------------------- 1 | { 2 | "logger": { 3 | "dir": "logs/", 4 | "level": "INFO", 5 | "keepHours": 24 6 | }, 7 | "db": { 8 | "maxmind": "internal.mmdb.test", 9 | "qqzengip": "", 10 | "ipdb":"" 11 | }, 12 | "source": { 13 | "ipv4": "maxmind", 14 | "ipv6": "maxmind" 15 | }, 16 | "autoDownload":{ 17 | "enabled":false 18 | }, 19 | "http": { 20 | "listen": "0.0.0.0:80", 21 | "trustProxy": ["127.0.0.1", "::1"], 22 | "cors":["http://localhost"], 23 | "x-api-key": "this-is-key" 24 | } 25 | } -------------------------------------------------------------------------------- /models/internal.mmdb.test: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ECNU/open-geoip/1eb64cd64c4856c5e2624e9d19b205c71073e350/models/internal.mmdb.test -------------------------------------------------------------------------------- /models/ip.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "fmt" 5 | "github.com/oschwald/geoip2-golang" 6 | "net" 7 | "strings" 8 | 9 | "github.com/ECNU/open-geoip/g" 10 | "github.com/ECNU/open-geoip/util" 11 | "github.com/ipipdotnet/ipdb-go" 12 | ) 13 | 14 | type IpGeo struct { 15 | IP string `json:"ip"` //IP地址 16 | Continent string `json:"continent"` //州 17 | Country string `json:"country"` //国家 18 | Province string `json:"province"` //省 19 | City string `json:"city"` //城市 20 | District string `json:"district"` //区县(行政区) 21 | ISP string `json:"isp"` //运营商 22 | AreaCode string `json:"areaCode"` //行政区划代码(国内) 23 | CountryEnglish string `json:"countryEnglish"` //国家英文名 24 | CountryCode string `json:"countryCode"` //国家英文代码 25 | Longitude string `json:"longitude"` //经度 26 | Latitude string `json:"latitude"` //纬度 27 | } 28 | 29 | type IpReader struct { 30 | MaxMindReader *geoip2.Reader 31 | InternalMaxMindReader *InternalReader 32 | QqzengReader *IpSearch 33 | IpdbReader *ipdb.City 34 | } 35 | 36 | var ipReader *IpReader 37 | 38 | func InitReader() error { 39 | ipReader = &IpReader{} 40 | if g.Config().DB.Qqzengip != "" { 41 | instance, err := LoadDat(g.Config().DB.Qqzengip) 42 | if err != nil { 43 | return err 44 | } 45 | ipReader.QqzengReader = instance 46 | } 47 | if g.Config().DB.Ipdb != "" { 48 | city, err := ipdb.NewCity(g.Config().DB.Ipdb) 49 | if err != nil { 50 | return err 51 | } 52 | ipReader.IpdbReader = city 53 | 54 | } 55 | 56 | if g.Config().Source.IPv4 == "maxmind" || g.Config().Source.IPv6 == "maxmind" { 57 | if g.Config().AutoDownload.Enabled { 58 | dbPath, err := util.AutoDownloadMaxmindDatabase(g.Config().AutoDownload) 59 | if err != nil { 60 | return err 61 | } 62 | db, err := geoip2.Open(dbPath) 63 | if err != nil { 64 | return err 65 | } 66 | ipReader.MaxMindReader = db 67 | 68 | } else { 69 | db, err := geoip2.Open(g.Config().DB.Maxmind) 70 | if err != nil { 71 | return err 72 | } 73 | ipReader.MaxMindReader = db 74 | } 75 | } 76 | 77 | if g.Config().InternalDB.Enabled { 78 | db, err := Open(g.Config().InternalDB.DB) 79 | if err != nil { 80 | return err 81 | } 82 | ipReader.InternalMaxMindReader = db 83 | } 84 | 85 | return nil 86 | } 87 | 88 | func copyIPdb(src *ipdb.CityInfo, dst *IpGeo, language string) { 89 | dst.AreaCode = src.ChinaAdminCode 90 | dst.City = src.CityName 91 | dst.Continent = src.ContinentCode 92 | dst.Country = src.CountryName 93 | dst.CountryCode = src.CountryCode 94 | dst.District = src.DistrictName 95 | dst.ISP = src.IspDomain 96 | dst.Latitude = src.Latitude 97 | dst.Longitude = src.Longitude 98 | dst.Province = src.RegionName 99 | return 100 | } 101 | 102 | // Todo 国际化拓展 103 | func switchIpdbLanguage(lan string) string { 104 | switch lan { 105 | case "zh-CN": 106 | return "CN" 107 | default: 108 | return "CN" 109 | } 110 | } 111 | 112 | func readSource(ipNet net.IP, source, language string) (ipGeo IpGeo, err error) { 113 | ipGeo.IP = ipNet.String() 114 | 115 | switch source { 116 | case "maxmind": 117 | 118 | var record *geoip2.City 119 | record, err = ipReader.MaxMindReader.City(ipNet) 120 | 121 | if err != nil { 122 | return 123 | } 124 | 125 | copyGeoIP(record, &ipGeo, language) 126 | 127 | return 128 | case "qqzengip": 129 | ipGeo = ipReader.QqzengReader.Get(ipNet.String()) 130 | return 131 | case "ipdb": 132 | lan := switchIpdbLanguage(language) 133 | var cityInfo *ipdb.CityInfo 134 | cityInfo, err = ipReader.IpdbReader.FindInfo(ipNet.String(), lan) 135 | if err != nil { 136 | return 137 | } 138 | copyIPdb(cityInfo, &ipGeo, language) 139 | return 140 | default: 141 | return 142 | } 143 | return 144 | } 145 | 146 | func copyGeoIP(src *geoip2.City, dst *IpGeo, language string) { 147 | if _, ok := src.Continent.Names[language]; ok { 148 | dst.Continent = src.Continent.Names[language] 149 | } 150 | if _, ok := src.Country.Names[language]; ok { 151 | dst.Country = src.Country.Names[language] 152 | } 153 | if _, ok := src.Country.Names["en"]; ok { 154 | dst.CountryEnglish = src.Country.Names["en"] 155 | } 156 | if _, ok := src.City.Names[language]; ok { 157 | dst.City = src.City.Names[language] 158 | } 159 | dst.CountryCode = src.Country.IsoCode 160 | if len(src.Subdivisions) > 0 { 161 | dst.Province = src.Subdivisions[0].Names[language] 162 | } 163 | dst.Latitude = fmt.Sprintf("%f", src.Location.Latitude) 164 | dst.Longitude = fmt.Sprintf("%f", src.Location.Longitude) 165 | 166 | return 167 | } 168 | 169 | func copyInternalGeoIP(src *InternalGeoIP, dst *IpGeo, language string) { 170 | if _, ok := src.City.Continent.Names[language]; ok { 171 | dst.Continent = src.City.Continent.Names[language] 172 | } 173 | if _, ok := src.City.Country.Names[language]; ok { 174 | dst.Country = src.City.Country.Names[language] 175 | } 176 | if _, ok := src.City.Country.Names["en"]; ok { 177 | dst.CountryEnglish = src.City.Country.Names["en"] 178 | } 179 | if _, ok := src.City.City.Names[language]; ok { 180 | dst.City = src.City.City.Names[language] 181 | } 182 | dst.CountryCode = src.City.Country.IsoCode 183 | dst.AreaCode = src.Internal.AreaCode 184 | if len(src.City.Subdivisions) > 0 { 185 | dst.Province = src.City.Subdivisions[0].Names[language] 186 | } 187 | if _, ok := src.Internal.ISP[language]; ok { 188 | dst.ISP = src.Internal.ISP[language] 189 | } 190 | if _, ok := src.Internal.District[language]; ok { 191 | dst.District = src.Internal.District[language] 192 | } 193 | dst.Latitude = fmt.Sprintf("%f", src.City.Location.Latitude) 194 | dst.Longitude = fmt.Sprintf("%f", src.City.Location.Longitude) 195 | 196 | return 197 | } 198 | 199 | func readInternalSource(ipNet net.IP, source, language string) (ipGeo IpGeo, err error) { 200 | ipGeo.IP = ipNet.String() 201 | switch source { 202 | case "maxmind": 203 | 204 | var record *InternalGeoIP 205 | 206 | record, err = ipReader.InternalMaxMindReader.City(ipNet) 207 | 208 | if err != nil { 209 | return 210 | } 211 | 212 | copyInternalGeoIP(record, &ipGeo, language) 213 | return 214 | } 215 | 216 | return 217 | } 218 | 219 | func GetIP(ipStr string, config g.SourceConfig, isApi bool, isAuth bool) (ipGeo IpGeo, err error) { 220 | //ToDO 支持国际化 221 | language := "zh-CN" 222 | ipGeo.IP = ipStr 223 | ipNet := net.ParseIP(ipStr) 224 | if ipNet == nil { 225 | err = fmt.Errorf("invalid IP address format: %s", ipStr) 226 | return 227 | } 228 | // 本地优先 229 | if g.Config().InternalDB.Enabled { 230 | 231 | enableInternalDB := true 232 | 233 | if isApi == false { 234 | if g.Config().InternalDB.Auth { 235 | if isAuth == false { 236 | enableInternalDB = false 237 | } 238 | } 239 | } 240 | 241 | if enableInternalDB { 242 | ipGeo, err = readInternalSource(ipNet, g.Config().InternalDB.Source, language) 243 | if err != nil { 244 | return 245 | } 246 | 247 | // ToString 9个字段 为空是8 248 | if len(ipGeo.ToString()) != 8 { 249 | return 250 | } 251 | } 252 | 253 | } 254 | 255 | //ipv6 256 | if strings.Contains(ipStr, ":") { 257 | 258 | ipGeo, err = readSource(ipNet, config.IPv6, language) 259 | if err != nil { 260 | return 261 | } 262 | return 263 | } 264 | //ipv4 265 | ipGeo, err = readSource(ipNet, config.IPv4, language) 266 | if err != nil { 267 | return 268 | } 269 | return 270 | } 271 | -------------------------------------------------------------------------------- /models/ip_test.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "log" 5 | "testing" 6 | 7 | "github.com/ECNU/open-geoip/g" 8 | "github.com/toolkits/file" 9 | 10 | "github.com/stretchr/testify/assert" 11 | ) 12 | 13 | func init() { 14 | g.ParseConfig("cfg.json.test") 15 | if file.IsExist("qqzeng-ip-3.0-ultimate.dat") { 16 | g.Config().DB.Qqzengip = "qqzeng-ip-3.0-ultimate.dat" 17 | } 18 | if file.IsExist("city.free.ipdb") { 19 | g.Config().DB.Ipdb = "city.free.ipdb" 20 | } 21 | err := InitReader() 22 | if err != nil { 23 | log.Fatalf("load geo db failed, %v", err) 24 | } 25 | } 26 | 27 | func Test_IpCheck(t *testing.T) { 28 | 29 | var campusIPs = []string{ 30 | "10.10.10.0/8", 31 | "192.168.0.0/24", 32 | "172.16.0.0/12", 33 | "192.168.10.1-192.168.10.250", 34 | "192.168.100.3", 35 | "2001:da8:8005::/48", 36 | } 37 | 38 | var ipCheckList = []struct { 39 | ip string 40 | exp bool 41 | }{ 42 | {"10.10.3.1", true}, 43 | {"192.168.12.3", false}, 44 | {"192.168.100.3", true}, 45 | {"192.168.10.100", true}, 46 | {"172.20.3.10", true}, 47 | {"8.8.8.8", false}, 48 | {"1.1.1.1", false}, 49 | {"2001:da8:8005:abcd:1234::8888", true}, 50 | {"2001:da8:8000:abcd:1234::8888", false}, 51 | } 52 | 53 | for _, r := range ipCheckList { 54 | out := IPCheck(r.ip, campusIPs) 55 | assert.Equal(t, out, r.exp) 56 | } 57 | } 58 | 59 | func Test_GetIP(t *testing.T) { 60 | 61 | res, _ := GetIP("192.168.0.1", g.Config().Source, false, false) 62 | assert.Equal(t, res.Country, "中国") 63 | res, _ = GetIP("fd12:3456:789a:bcde::1", g.Config().Source, false, false) 64 | assert.Equal(t, res.Country, "中国") 65 | 66 | if file.IsExist("city.free.ipdb") { 67 | g.Config().Source.IPv4 = "ipdb" 68 | res, _ = GetIP("114.114.114.114", g.Config().Source, false, false) 69 | t.Log(res) 70 | assert.Equal(t, res.Country, "114DNS.COM") 71 | } 72 | if file.IsExist("qqzeng-ip-3.0-ultimate.dat") { 73 | g.Config().Source.IPv4 = "qqzengip" 74 | res, _ = GetIP("202.120.92.60", g.Config().Source, false, false) 75 | t.Log(res) 76 | assert.Equal(t, res.ISP, "教育网") 77 | } 78 | //非法的请求 79 | _, err := GetIP("201..1", g.Config().Source, false, false) 80 | assert.NotNil(t, err) 81 | _, err = GetIP("2001:da8:::::::::", g.Config().Source, false, false) 82 | assert.NotNil(t, err) 83 | } 84 | 85 | func TestSearchIP(t *testing.T) { 86 | g.Config().Source.IPv4 = "maxmind" 87 | res := SearchIP("192.168.0.1", false, false) 88 | assert.Equal(t, res.Province, "上海") 89 | assert.Equal(t, res.IP, "192.168.0.1") 90 | res = SearchIP("fd12:3456:789a:bcde::1", false, false) 91 | assert.Equal(t, res.Country, "中国") 92 | assert.Equal(t, res.IP, "fd12:3456:789a:bcde::1") 93 | 94 | //非法的请求 95 | res = SearchIP("202..1", false, false) 96 | assert.Equal(t, res.IP, "202..1") 97 | assert.Equal(t, res.Country, "") 98 | res = SearchIP("202:da8:::::::", false, false) 99 | assert.Equal(t, res.IP, "202:da8:::::::") 100 | assert.Equal(t, res.Country, "") 101 | } 102 | 103 | func Benchmark_maxmind(b *testing.B) { 104 | for i := 0; i < b.N; i++ { 105 | SearchIP("202.120.92.60", false, false) 106 | } 107 | } 108 | 109 | func Benchmark_Ipdb(b *testing.B) { 110 | if !file.IsExist("city.free.ipdb") { 111 | return 112 | } 113 | g.Config().Source.IPv4 = "ipdb" 114 | for i := 0; i < b.N; i++ { 115 | SearchIP("202.120.92.60", false, false) 116 | } 117 | } 118 | 119 | func Benchmark_qqzengip(b *testing.B) { 120 | if !file.IsExist("qqzeng-ip-3.0-ultimate.dat") { 121 | return 122 | } 123 | g.Config().Source.IPv4 = "qqzengip" 124 | for i := 0; i < b.N; i++ { 125 | SearchIP("202.120.92.60", false, false) 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /models/iprange.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "encoding/binary" 5 | "net" 6 | 7 | "strings" 8 | ) 9 | 10 | // IPCheck 检查 ip 是否在特定的 ip 地址范围内 11 | func IPCheck(thisip string, ips []string) bool { 12 | for _, ip := range ips { 13 | ip = strings.TrimRight(ip, "/") 14 | if strings.Contains(ip, "/") { 15 | if ipCheckMask(thisip, ip) { 16 | return true 17 | } 18 | } else if strings.Contains(ip, "-") { 19 | ipRange := strings.SplitN(ip, "-", 2) 20 | if ipCheckRange(thisip, ipRange[0], ipRange[1]) { 21 | return true 22 | } 23 | } else { 24 | if thisip == ip { 25 | return true 26 | } 27 | } 28 | } 29 | return false 30 | } 31 | 32 | func ipCheckRange(ip, ipStart, ipEnd string) bool { 33 | thisIP := net.ParseIP(ip) 34 | firstIP := net.ParseIP(ipStart) 35 | endIP := net.ParseIP(ipEnd) 36 | if thisIP.To4() == nil || firstIP.To4() == nil || endIP.To4() == nil { 37 | return false 38 | } 39 | firstIPNum := ipToInt(firstIP.To4()) 40 | endIPNum := ipToInt(endIP.To4()) 41 | thisIPNum := ipToInt(thisIP.To4()) 42 | if thisIPNum >= firstIPNum && thisIPNum <= endIPNum { 43 | return true 44 | } 45 | return false 46 | } 47 | 48 | func ipCheckMask(ip, ipMask string) bool { 49 | _, subnet, _ := net.ParseCIDR(ipMask) 50 | 51 | thisIP := net.ParseIP(ip) 52 | return subnet.Contains(thisIP) 53 | } 54 | 55 | func ipToInt(ip net.IP) int32 { 56 | return int32(binary.BigEndian.Uint32(ip.To4())) 57 | } 58 | -------------------------------------------------------------------------------- /models/qqzengip.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "encoding/binary" 5 | "errors" 6 | "io/ioutil" 7 | "log" 8 | "net" 9 | "strconv" 10 | "strings" 11 | "sync" 12 | ) 13 | 14 | type IpSearch struct { 15 | prefStart [256]uint32 16 | prefEnd [256]uint32 17 | endArr []uint32 18 | addrArr []string 19 | } 20 | 21 | var instance *IpSearch 22 | var once sync.Once 23 | 24 | func GetInstance() *IpSearch { 25 | once.Do(func() { 26 | instance = &IpSearch{} 27 | var err error 28 | instance, err = LoadDat("./qqzeng-ip-3.0-ultimate.dat") 29 | if err != nil { 30 | log.Fatal("the IP Dat loaded failed!") 31 | } 32 | }) 33 | return instance 34 | } 35 | 36 | func LoadDat(file string) (*IpSearch, error) { 37 | p := IpSearch{} 38 | data, err := ioutil.ReadFile(file) 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | for k := 0; k < 256; k++ { 44 | i := k*8 + 4 45 | p.prefStart[k] = ReadLittleEndian32(data[i], data[i+1], data[i+2], data[i+3]) 46 | p.prefEnd[k] = ReadLittleEndian32(data[i+4], data[i+5], data[i+6], data[i+7]) 47 | } 48 | 49 | RecordSize := int(ReadLittleEndian32(data[0], data[1], data[2], data[3])) 50 | 51 | p.endArr = make([]uint32, RecordSize) 52 | p.addrArr = make([]string, RecordSize) 53 | for i := 0; i < RecordSize; i++ { 54 | j := 2052 + (i * 8) 55 | endipnum := ReadLittleEndian32(data[j], data[1+j], data[2+j], data[3+j]) 56 | offset := ReadLittleEndian24(data[4+j], data[5+j], data[6+j]) 57 | length := uint32(data[7+j]) 58 | p.endArr[i] = endipnum 59 | p.addrArr[i] = string(data[offset:int(offset+length)]) 60 | } 61 | return &p, err 62 | 63 | } 64 | 65 | func (p *IpSearch) Get(ip string) (ipGeo IpGeo) { 66 | intIP, err := ip2Long(ip) 67 | if err != nil { 68 | return 69 | } 70 | 71 | ips := strings.Split(ip, ".") 72 | x, _ := strconv.Atoi(ips[0]) 73 | prefix := uint32(x) 74 | 75 | low := p.prefStart[prefix] 76 | high := p.prefEnd[prefix] 77 | 78 | var cur uint32 79 | if low == high { 80 | cur = low 81 | } else { 82 | cur = p.binarySearch(low, high, intIP) 83 | } 84 | 85 | ipSlice := strings.Split(p.addrArr[cur], "|") 86 | if len(ipSlice) != 11 { 87 | ipGeo.IP = ip 88 | return 89 | } 90 | 91 | ipGeo = IpGeo{ 92 | IP: ip, 93 | Continent: ipSlice[0], 94 | Country: ipSlice[1], 95 | Province: ipSlice[2], 96 | City: ipSlice[3], 97 | District: ipSlice[4], 98 | ISP: ipSlice[5], 99 | AreaCode: ipSlice[6], 100 | CountryEnglish: ipSlice[7], 101 | CountryCode: ipSlice[8], 102 | Longitude: ipSlice[9], 103 | Latitude: ipSlice[10], 104 | } 105 | return 106 | } 107 | 108 | func (p *IpSearch) binarySearch(low uint32, high uint32, k uint32) uint32 { 109 | var M uint32 = 0 110 | for low <= high { 111 | mid := (low + high) / 2 112 | endipNum := p.endArr[mid] 113 | if endipNum >= k { 114 | M = mid 115 | if mid == 0 { 116 | break 117 | } 118 | high = mid - 1 119 | } else { 120 | low = mid + 1 121 | } 122 | } 123 | return M 124 | } 125 | 126 | func ip2Long(ipstr string) (uint32, error) { 127 | ip := net.ParseIP(ipstr) 128 | ip = ip.To4() 129 | if ip == nil { 130 | err := errors.New("qqzengip only support ipv4") 131 | return 0, err 132 | } 133 | return binary.BigEndian.Uint32(ip), nil 134 | } 135 | 136 | func ReadLittleEndian32(a, b, c, d byte) uint32 { 137 | return (uint32(a) & 0xFF) | ((uint32(b) << 8) & 0xFF00) | ((uint32(c) << 16) & 0xFF0000) | ((uint32(d) << 24) & 0xFF000000) 138 | } 139 | 140 | func ReadLittleEndian24(a, b, c byte) uint32 { 141 | return (uint32(a) & 0xFF) | ((uint32(b) << 8) & 0xFF00) | ((uint32(c) << 16) & 0xFF0000) 142 | } 143 | -------------------------------------------------------------------------------- /models/ratelimit.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "strconv" 7 | 8 | "github.com/ECNU/open-geoip/g" 9 | "github.com/gomodule/redigo/redis" 10 | "github.com/toolkits/pkg/logger" 11 | ) 12 | 13 | const ( 14 | Minute = "minute" 15 | MinuteTTL = 60 16 | Hour = "hour" 17 | HourTTL = 3600 18 | Day = "day" 19 | DayTTL = 86400 20 | NameSpace = "open-geoip:rate:limit:" 21 | ) 22 | 23 | func SetQueryRateLimit(enabled bool, clientIP string) error { 24 | if !enabled { 25 | return nil 26 | } 27 | redisPool := g.ConnectRedis() 28 | var count int 29 | var locked bool 30 | if g.Config().RateLimit.Day > 0 { 31 | count, locked = setQueryRateDay(redisPool, clientIP, g.Config().RateLimit.Day) 32 | if locked == true { 33 | err := fmt.Errorf("每日请求计数值达到 %d, %s 已经被锁定", count, clientIP) 34 | return err 35 | } 36 | } 37 | if g.Config().RateLimit.Hour > 0 { 38 | count, locked = setQueryRateHour(redisPool, clientIP, g.Config().RateLimit.Hour) 39 | if locked == true { 40 | err := fmt.Errorf("每小时请求计数值达到 %d, %s 已经被锁定", count, clientIP) 41 | return err 42 | } 43 | } 44 | if g.Config().RateLimit.Minute > 0 { 45 | count, locked = setQueryRateMinute(redisPool, clientIP, g.Config().RateLimit.Minute) 46 | if locked == true { 47 | err := fmt.Errorf("每分钟请求计数值达到 %d, %s 已经被锁定", count, clientIP) 48 | return err 49 | } 50 | } 51 | return nil 52 | } 53 | 54 | func ClearRateLimit(clientIP string) (err error) { 55 | conn := g.ConnectRedis().Get() 56 | minKey := NameSpace + Minute + ":" + clientIP 57 | _, err = conn.Do("DEL", minKey) 58 | if err != nil { 59 | return 60 | } 61 | hourKey := NameSpace + Hour + ":" + clientIP 62 | _, err = conn.Do("DEL", hourKey) 63 | if err != nil { 64 | return 65 | } 66 | dayKey := NameSpace + Day + ":" + clientIP 67 | _, err = conn.Do("DEL", dayKey) 68 | if err != nil { 69 | return 70 | } 71 | return 72 | } 73 | 74 | type CurrentRateCount struct { 75 | MinuteCount RateCount `json:"minuteCount"` 76 | HourCount RateCount `json:"hourCount"` 77 | DayCount RateCount `json:"dayCount"` 78 | } 79 | 80 | type RateCount struct { 81 | Count int `json:"count"` 82 | Expire int `json:"expire"` 83 | } 84 | 85 | func GetCurrentRateCount(clientIP string) (res CurrentRateCount, err error) { 86 | redisPool := g.ConnectRedis() 87 | res.MinuteCount.Count, res.MinuteCount.Expire, err = getCurrentRateCount(redisPool, Minute, clientIP) 88 | if err != nil { 89 | return 90 | } 91 | res.HourCount.Count, res.HourCount.Expire, err = getCurrentRateCount(redisPool, Hour, clientIP) 92 | if err != nil { 93 | return 94 | } 95 | res.DayCount.Count, res.DayCount.Expire, err = getCurrentRateCount(redisPool, Day, clientIP) 96 | if err != nil { 97 | return 98 | } 99 | return 100 | } 101 | 102 | func getCurrentRateCount(redisPool *redis.Pool, mode, clientIP string) (count, expire int, err error) { 103 | if mode != Minute && mode != Hour && mode != Day { 104 | err = errors.New("不是合法的 mode") 105 | return 106 | } 107 | conn := redisPool.Get() 108 | defer conn.Close() 109 | redisKey := NameSpace + mode + ":" + clientIP 110 | res, err := conn.Do("GET", redisKey) 111 | if err != nil { 112 | return 113 | } 114 | if res == nil { 115 | return 116 | } 117 | value := string(res.([]byte)) 118 | count, err = strconv.Atoi(value) 119 | if err != nil { 120 | logger.Error(err) 121 | } 122 | ttl, err := conn.Do("TTL", redisKey) 123 | if err != nil { 124 | return 125 | } 126 | expire = int(ttl.(int64)) 127 | return 128 | } 129 | 130 | func setQueryRateMinute(redisPool *redis.Pool, clientIP string, limit int) (count int, locked bool) { 131 | conn := redisPool.Get() 132 | defer conn.Close() 133 | redisKey := NameSpace + Minute + ":" + clientIP 134 | 135 | // 使用 INCR 命令对键进行原子递增操作,并返回当前的计数值 136 | count, err := redis.Int(conn.Do("INCR", redisKey)) 137 | if err != nil { 138 | logger.Error(err) 139 | return 140 | } 141 | // 如果这个键是第一次被创建,就使用 EXPIRE 命令为其设置过期时间为 60 秒 142 | if count == 1 { 143 | _, err := conn.Do("EXPIRE", redisKey, MinuteTTL) 144 | if err != nil { 145 | logger.Error(err) 146 | return 147 | } 148 | } 149 | // 根据计数值和限制值进行比较,如果超过了限制值,就返回 locked = true,否则返回 locked = false 150 | if count > limit { 151 | locked = true 152 | } 153 | return 154 | } 155 | 156 | func setQueryRateHour(redisPool *redis.Pool, clientIP string, limit int) (count int, locked bool) { 157 | conn := redisPool.Get() 158 | defer conn.Close() 159 | redisKey := NameSpace + Hour + ":" + clientIP 160 | 161 | // 使用 INCR 命令对键进行原子递增操作,并返回当前的计数值 162 | count, err := redis.Int(conn.Do("INCR", redisKey)) 163 | if err != nil { 164 | logger.Error(err) 165 | return 166 | } 167 | // 如果这个键是第一次被创建,就使用 EXPIRE 命令为其设置过期时间为 3600 秒 168 | if count == 1 { 169 | _, err := conn.Do("EXPIRE", redisKey, HourTTL) 170 | if err != nil { 171 | logger.Error(err) 172 | return 173 | } 174 | } 175 | // 根据计数值和限制值进行比较,如果超过了限制值,就返回 locked = true,否则返回 locked = false 176 | if count > limit { 177 | locked = true 178 | } 179 | return 180 | } 181 | 182 | func setQueryRateDay(redisPool *redis.Pool, clientIP string, limit int) (count int, locked bool) { 183 | conn := redisPool.Get() 184 | defer conn.Close() 185 | redisKey := NameSpace + Day + ":" + clientIP 186 | 187 | // 使用 INCR 命令对键进行原子递增操作,并返回当前的计数值 188 | count, err := redis.Int(conn.Do("INCR", redisKey)) 189 | if err != nil { 190 | logger.Error(err) 191 | return 192 | } 193 | // 如果这个键是第一次被创建,就使用 EXPIRE 命令为其设置过期时间为 3600 秒 194 | if count == 1 { 195 | _, err := conn.Do("EXPIRE", redisKey, DayTTL) 196 | if err != nil { 197 | logger.Error(err) 198 | return 199 | } 200 | } 201 | // 根据计数值和限制值进行比较,如果超过了限制值,就返回 locked = true,否则返回 locked = false 202 | if count > limit { 203 | locked = true 204 | } 205 | return 206 | } 207 | -------------------------------------------------------------------------------- /models/ratelimit_test.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "fmt" 5 | 6 | "testing" 7 | 8 | "github.com/alicebob/miniredis/v2" 9 | "github.com/gomodule/redigo/redis" 10 | "github.com/stretchr/testify/assert" 11 | ) 12 | 13 | func Test_RateLimit(t *testing.T) { 14 | // 启动一个 Redis 服务器 15 | s, err := miniredis.Run() 16 | if err != nil { 17 | t.Fatal(err) 18 | } 19 | defer s.Close() 20 | 21 | clientIP := "192.168.0.1" // 模拟客户端 IP 22 | limit := 10 // 设置每分钟的请求限制为 10 次 23 | 24 | for i := 0; i < 15; i++ { 25 | // 创建一个 Redis 连接 26 | conn, err := redis.Dial("tcp", s.Addr()) 27 | if err != nil { 28 | panic(err) 29 | } 30 | defer conn.Close() 31 | 32 | rc := &redis.Pool{ 33 | Dial: func() (redis.Conn, error) { 34 | return conn, nil 35 | }, 36 | } 37 | count, locked := setQueryRateMinute(rc, clientIP, limit) 38 | fmt.Printf("第 %d 次请求,计数值为 %d,是否被锁定:%v\n", i+1, count, locked) 39 | if i < 10 { 40 | assert.Equal(t, locked, false) 41 | } 42 | if i >= 10 { 43 | assert.Equal(t, locked, true) 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /models/reader.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "fmt" 5 | "github.com/oschwald/geoip2-golang" 6 | "github.com/oschwald/maxminddb-golang" 7 | "net" 8 | ) 9 | 10 | const ( 11 | isAnonymousIP = 1 << iota 12 | isASN 13 | isCity 14 | isConnectionType 15 | isCountry 16 | isDomain 17 | isEnterprise 18 | isISP 19 | ) 20 | 21 | func getDBType(reader *maxminddb.Reader) (databaseType, error) { 22 | switch reader.Metadata.DatabaseType { 23 | case "GeoIP2-Anonymous-IP": 24 | return isAnonymousIP, nil 25 | case "DBIP-ASN-Lite (compat=GeoLite2-ASN)", 26 | "GeoLite2-ASN": 27 | return isASN, nil 28 | // We allow City lookups on Country for back compat 29 | case "DBIP-City-Lite", 30 | "DBIP-Country-Lite", 31 | "DBIP-Country", 32 | "DBIP-Location (compat=City)", 33 | "GeoLite2-City", 34 | "GeoIP2-City", 35 | "GeoIP2-City-Africa", 36 | "GeoIP2-City-Asia-Pacific", 37 | "GeoIP2-City-Europe", 38 | "GeoIP2-City-North-America", 39 | "GeoIP2-City-South-America", 40 | "GeoIP2-Precision-City", 41 | "GeoLite2-Country", 42 | "GeoIP2-Country": 43 | return isCity | isCountry, nil 44 | case "GeoIP2-Connection-Type": 45 | return isConnectionType, nil 46 | case "GeoIP2-Domain": 47 | return isDomain, nil 48 | case "DBIP-ISP (compat=Enterprise)", 49 | "DBIP-Location-ISP (compat=Enterprise)", 50 | "GeoIP2-Enterprise": 51 | return isEnterprise | isCity | isCountry, nil 52 | case "GeoIP2-ISP", 53 | "GeoIP2-Precision-ISP": 54 | return isISP | isASN, nil 55 | default: 56 | return 0, UnknownDatabaseTypeError{reader.Metadata.DatabaseType} 57 | } 58 | } 59 | 60 | type InternalGeoIP struct { 61 | geoip2.City 62 | Internal struct { 63 | ISP map[string]string `maxminddb:"isp"` 64 | District map[string]string `maxminddb:"district"` 65 | AreaCode string `maxminddb:"areaCode"` 66 | } `maxminddb:"internal"` 67 | } 68 | 69 | type databaseType int 70 | 71 | type InternalReader struct { 72 | mmdbReader *maxminddb.Reader 73 | databaseType databaseType 74 | } 75 | 76 | type InvalidMethodError struct { 77 | Method string 78 | DatabaseType string 79 | } 80 | 81 | func (e InvalidMethodError) Error() string { 82 | return fmt.Sprintf(`geoip2: the %s method does not support the %s database`, 83 | e.Method, e.DatabaseType) 84 | } 85 | 86 | // UnknownDatabaseTypeError is returned when an unknown database type is 87 | // opened. 88 | type UnknownDatabaseTypeError struct { 89 | DatabaseType string 90 | } 91 | 92 | func (e UnknownDatabaseTypeError) Error() string { 93 | return fmt.Sprintf(`geoip2: reader does not support the %q database type`, 94 | e.DatabaseType) 95 | } 96 | 97 | func (r *InternalReader) Metadata() maxminddb.Metadata { 98 | 99 | fmt.Printf("dsadasdasdsdas\n") 100 | return r.mmdbReader.Metadata 101 | } 102 | 103 | func Open(file string) (*InternalReader, error) { 104 | reader, err := maxminddb.Open(file) 105 | if err != nil { 106 | return nil, err 107 | } 108 | dbType, err := getDBType(reader) 109 | return &InternalReader{reader, dbType}, err 110 | } 111 | 112 | func (r *InternalReader) Close() error { 113 | return r.mmdbReader.Close() 114 | } 115 | 116 | func (r *InternalReader) City(ipAddress net.IP) (*InternalGeoIP, error) { 117 | 118 | if isCity&r.databaseType == 0 { 119 | return nil, InvalidMethodError{"City", r.Metadata().DatabaseType} 120 | } 121 | var city InternalGeoIP 122 | err := r.mmdbReader.Lookup(ipAddress, &city) 123 | return &city, err 124 | } 125 | -------------------------------------------------------------------------------- /models/search.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | 7 | "github.com/ECNU/open-geoip/g" 8 | "github.com/toolkits/pkg/logger" 9 | ) 10 | 11 | func (self IpGeo) ToString() string { 12 | //只返回必要的部分,给前端先使用 13 | res := fmt.Sprintf("%s %s %s %s %s %s %s %s %s", self.Continent, self.Country, self.CountryEnglish, self.CountryCode, self.AreaCode, self.Province, self.City, self.District, self.ISP) 14 | return res 15 | } 16 | 17 | func SearchIP(ipStr string, isApi bool, isAuth bool) (result IpGeo) { 18 | //无论发生什么,IP 永远返回 19 | result.IP = ipStr 20 | 21 | var err error 22 | result, err = GetIP(ipStr, g.Config().Source, isApi, isAuth) 23 | 24 | if err != nil { 25 | logger.Error(err) 26 | return 27 | } 28 | return 29 | } 30 | 31 | func CheckIPValid(ipStr string) bool { 32 | ipNet := net.ParseIP(ipStr) 33 | if ipNet == nil { 34 | return false 35 | } 36 | return true 37 | } 38 | -------------------------------------------------------------------------------- /open-geoip.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=open-geoip 3 | After=network-online.target 4 | Wants=network-online.target 5 | 6 | [Service] 7 | # modify when deploy in prod env 8 | User=root 9 | Group=root 10 | 11 | Type=simple 12 | ExecStart=/opt/open-geoip/open-geoip 13 | WorkingDirectory=/opt/open-geoip 14 | 15 | Restart=always 16 | RestartSec=1 17 | StartLimitInterval=0 18 | 19 | [Install] 20 | WantedBy=multi-user.target 21 | 22 | -------------------------------------------------------------------------------- /templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Open-GeoIP 5 | 6 | 7 | 8 | 9 | 15 | 16 | 17 | 18 |
19 | 46 |
47 |
48 |
49 |
50 |
51 |

open-geoip

52 |

53 |

54 |
55 |
56 |
57 |
58 | 60 |
61 |
62 |
63 |
64 | 65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 | 120 | 121 | 204 | 205 | 206 | 207 | -------------------------------------------------------------------------------- /util/auth.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "io/ioutil" 5 | "net/http" 6 | 7 | "github.com/ECNU/open-geoip/g" 8 | jsoniter "github.com/json-iterator/go" 9 | ) 10 | 11 | type UserInfo struct { 12 | Username string `json:"Username"` 13 | Nickname string `json:"Nickname"` 14 | } 15 | 16 | // OauthUserInfo 获取用户信息 17 | func OauthUserInfo(accessToken string) (userInfo UserInfo, err error) { 18 | //fmt.Printf("%v\n", accessToken) 19 | client := &http.Client{} 20 | 21 | // 创建一个 http.NewRequest 对象 22 | req, err := http.NewRequest("GET", g.Config().Oauth2.UserInfoAddr, nil) 23 | if err != nil { 24 | //panic(err) 25 | return 26 | } 27 | req.Header.Add("Authorization", "Bearer "+accessToken) 28 | 29 | // 发送请求并获取响应 30 | resp, err := client.Do(req) 31 | if err != nil { 32 | //panic(err) 33 | return 34 | } 35 | defer resp.Body.Close() 36 | 37 | // 读取响应体 38 | responseBody, err := ioutil.ReadAll(resp.Body) 39 | if err != nil { 40 | //panic(err) 41 | return 42 | } 43 | 44 | userInfo.Username = getUserinfoField(responseBody, g.Config().Oauth2.UserinfoIsArray, g.Config().Oauth2.UserinfoPrefix, g.Config().Oauth2.Attributes.Username) 45 | userInfo.Nickname = getUserinfoField(responseBody, g.Config().Oauth2.UserinfoIsArray, g.Config().Oauth2.UserinfoPrefix, g.Config().Oauth2.Attributes.Nickname) 46 | 47 | return 48 | 49 | } 50 | 51 | func getUserinfoField(input []byte, isArray bool, prefix, field string) string { 52 | if prefix == "" { 53 | if isArray { 54 | return jsoniter.Get(input, 0).Get(field).ToString() 55 | } else { 56 | return jsoniter.Get(input, field).ToString() 57 | } 58 | } else { 59 | if isArray { 60 | return jsoniter.Get(input, prefix, 0).Get(field).ToString() 61 | } else { 62 | return jsoniter.Get(input, prefix).Get(field).ToString() 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /util/downloader.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "os" 5 | "time" 6 | 7 | "github.com/ECNU/open-geoip/g" 8 | geoip "github.com/pieterclaerhout/go-geoip/v2" 9 | "github.com/toolkits/pkg/logger" 10 | ) 11 | 12 | const ( 13 | DefaultDownloadTimeout = 3 14 | DefaultTargetFilePath = "./" 15 | ) 16 | 17 | func AutoDownloadMaxmindDatabase(config g.AutoDownloadConfig) (string, error) { 18 | if config.MaxmindLicenseKey == "" { 19 | config.MaxmindLicenseKey = os.Getenv("MAXMIND_LICENSE_KEY") 20 | } 21 | 22 | if config.Timeout == 0 { 23 | config.Timeout = DefaultDownloadTimeout 24 | } 25 | 26 | if config.TargetFilePath == "" { 27 | config.TargetFilePath = DefaultTargetFilePath 28 | } 29 | 30 | dbPath := config.TargetFilePath + "GeoLite2-City.mmdb" 31 | 32 | downloader := geoip.NewDatabaseDownloader(config.MaxmindLicenseKey, dbPath, time.Duration(config.Timeout)*time.Minute) 33 | 34 | logger.Debug("Checking if the database needs updating") 35 | 36 | localChecksum, err := downloader.LocalChecksum() 37 | if err != nil { 38 | return dbPath, err 39 | } 40 | 41 | remoteChecksum, err := downloader.RemoteChecksum() 42 | if err != nil { 43 | return dbPath, err 44 | } 45 | 46 | logger.Debug("Local checksum: ", localChecksum) 47 | logger.Debug("Remote checksum:", remoteChecksum) 48 | 49 | shouldDownload, err := downloader.ShouldDownload() 50 | if err != nil { 51 | return dbPath, err 52 | } 53 | 54 | if !shouldDownload { 55 | logger.Debug("Database is up-to-date, no download needed") 56 | return dbPath, nil 57 | } 58 | 59 | logger.Info("Database not found or outdated, downloading") 60 | 61 | if err := downloader.Download(); err != nil { 62 | return dbPath, err 63 | } 64 | 65 | logger.Info("Database downloaded succesfully") 66 | return dbPath, nil 67 | } 68 | -------------------------------------------------------------------------------- /util/string_util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "math/rand" 5 | "strings" 6 | "time" 7 | ) 8 | 9 | func init() { 10 | rand.Seed(time.Now().UnixNano()) 11 | } 12 | 13 | func InSliceStr(str string, slice []string) bool { 14 | for _, s := range slice { 15 | if str == s { 16 | return true 17 | } 18 | } 19 | return false 20 | } 21 | 22 | func InSliceStrFuzzy(str string, slice []string) bool { 23 | for _, s := range slice { 24 | if strings.Contains(str, s) || strings.Contains(s, str) { 25 | return true 26 | } 27 | } 28 | return false 29 | } 30 | 31 | var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") 32 | 33 | func RandStringRunes(n int) string { 34 | b := make([]rune, n) 35 | for i := range b { 36 | b[i] = letterRunes[rand.Intn(len(letterRunes))] 37 | } 38 | return string(b) 39 | } 40 | --------------------------------------------------------------------------------