├── .circleci └── config.yml ├── .github └── workflows │ └── notify-ci-status.yml ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── VERSION ├── discovery.go ├── discovery_test.go ├── go.mod ├── go.sum └── golang.mk /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | executors: 4 | common-executor: 5 | working_directory: ~/go/src/github.com/Clever/discovery-go 6 | docker: 7 | - image: cimg/go:1.24 8 | environment: 9 | CIRCLE_ARTIFACTS: /tmp/circleci-artifacts 10 | CIRCLE_TEST_REPORTS: /tmp/circleci-test-results 11 | GOPRIVATE: github.com/Clever/* 12 | 13 | commands: 14 | clone-ci-scripts: 15 | description: Clone the ci-scripts repo 16 | steps: 17 | - run: 18 | command: cd $HOME && git clone --depth 1 -v https://github.com/Clever/ci-scripts.git && cd ci-scripts && git show --oneline -s 19 | name: Clone ci-scripts 20 | 21 | jobs: 22 | build: 23 | executor: common-executor 24 | steps: 25 | - checkout 26 | - run: make install_deps 27 | - run: make test 28 | - persist_to_workspace: 29 | root: ~/go/src/github.com/Clever 30 | paths: "." 31 | - clone-ci-scripts 32 | - run: cd ~/go/src/github.com/Clever/discovery-go 33 | - run: if [ "${CIRCLE_BRANCH}" == "master" ]; then $HOME/ci-scripts/circleci/github-release $GH_RELEASE_TOKEN; fi; 34 | 35 | -------------------------------------------------------------------------------- /.github/workflows/notify-ci-status.yml: -------------------------------------------------------------------------------- 1 | name: Notify CI status 2 | 3 | on: 4 | check_suite: 5 | types: [completed] 6 | status: 7 | 8 | jobs: 9 | call-workflow: 10 | if: >- 11 | (github.event.branches[0].name == github.event.repository.default_branch && 12 | (github.event.state == 'error' || github.event.state == 'failure')) || 13 | (github.event.check_suite.head_branch == github.event.repository.default_branch && 14 | github.event.check_suite.conclusion != 'success') 15 | uses: Clever/ci-scripts/.github/workflows/reusable-notify-ci-status.yml@master 16 | secrets: 17 | CIRCLE_CI_INTEGRATIONS_URL: ${{ secrets.CIRCLE_CI_INTEGRATIONS_URL }} 18 | CIRCLE_CI_INTEGRATIONS_USERNAME: ${{ secrets.CIRCLE_CI_INTEGRATIONS_USERNAME }} 19 | CIRCLE_CI_INTEGRATIONS_PASSWORD: ${{ secrets.CIRCLE_CI_INTEGRATIONS_PASSWORD }} 20 | SLACK_BOT_TOKEN: ${{ secrets.DAPPLE_BOT_TOKEN }} 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | 26 | vendor/ 27 | -------------------------------------------------------------------------------- /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 {yyyy} {name of copyright owner} 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 | 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | include golang.mk 2 | .DEFAULT_GOAL := test # override default goal set in library makefile 3 | 4 | .PHONY: test $(PKGS) 5 | SHELL := /bin/bash 6 | PKGS = $(shell go list ./... | grep -v /vendor) 7 | $(eval $(call golang-version-check,1.24)) 8 | 9 | test: $(PKGS) 10 | $(PKGS): golang-test-all-strict-deps 11 | @go get -d -t $@ 12 | $(call golang-test-all-strict,$@) 13 | 14 | install_deps: 15 | go mod vendor 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # discovery-go 2 | 3 | This library programmatically finds endpoints for dependencies. Similar to [discovery-node](https://github.com/Clever/discovery-node) and [disocvery-python](https://github.com/Clever/discovery-python). 4 | 5 | 6 | See [Service Discovery](https://clever.atlassian.net/wiki/spaces/ENG/pages/116686857/Discovery) for more details. 7 | 8 | 9 | ## API 10 | 11 | [Godoc Documentation](http://godoc.org/github.com/Clever/discovery-go) 12 | 13 | ### Examples 14 | 15 | ```go 16 | gearmanAdminURLString, err := discovery.URL("gearman-admin", "http") 17 | if err != nil { 18 | log.Fatal("ERROR: " + err.Error()) 19 | } 20 | 21 | stokedHostPort, err := discovery.HostPort("stoked", "thrift") 22 | if err != nil { 23 | logger.Fatal("ERROR: " + err.Error()) 24 | } 25 | 26 | stokedHost, err := discovery.Host("stoked", "thrift") 27 | if err != nil { 28 | logger.Fatal("ERROR: " + err.Error()) 29 | } 30 | 31 | stokedPort, err := discovery.Port("stoked", "thrift") 32 | if err != nil { 33 | logger.Fatal("ERROR: " + err.Error()) 34 | } 35 | 36 | cleverComURL, err := discovery.ExternalURL("clever.com") 37 | if err != nil { 38 | logger.Fatal("ERROR: " + err.Error()) 39 | } 40 | ``` 41 | 42 | ### Implementation Details 43 | 44 | Currently, `discovery-{go,node,python}` looks for environment variables with the following format: 45 | 46 | ``` 47 | SERVICE_{SERVICE_NAME}_{EXPOSE_NAME}_{PROTO,HOST,PORT} 48 | ``` 49 | 50 | These environment variables are autogenerated [catapult](http://github.com/Clever/catapult) during app deployment. Three env-vars are created for each app listed in the `dependencies` section of caller's launch yaml. 51 | 52 | For example, if an app lists `district-authorizations` as a dependency, catapult will generate this env-vars triplet: 53 | 54 | ```bash 55 | SERVICE_DISTRICT_AUTHORIZATIONS_HTTP_PROTO = "http" 56 | SERVICE_DISTRICT_AUTHORIZATIONS_HTTP_HOST = "district-authorizations.ops.clever.com" 57 | SERVICE_DISTRICT_AUTHORIZATIONS_HTTP_PORT = "80" 58 | ``` 59 | 60 | It is also used to look for external urls with the format 61 | 62 | ``` 63 | EXTERNAL_URL_{URL_HOST} 64 | ``` 65 | 66 | For example for `schools.clever.com` catapult will set: 67 | 68 | ```bash 69 | EXTERNAL_URL_SCHOOLS_CLEVER_COM = "https://schools.clever.com:443 70 | ``` 71 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 1.9.1 2 | -------------------------------------------------------------------------------- /discovery.go: -------------------------------------------------------------------------------- 1 | package discovery 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | "net/url" 7 | "os" 8 | "strings" 9 | ) 10 | 11 | const ( 12 | templateVar = "SERVICE_%s_%s_%%s" 13 | externalURLVar = "EXTERNAL_URL_%s" 14 | ) 15 | 16 | func getVar(envVar string) (string, error) { 17 | envVar = strings.ToUpper(envVar) 18 | envVar = strings.Replace(envVar, "-", "_", -1) 19 | val := os.Getenv(envVar) 20 | if val == "" { 21 | return "", fmt.Errorf("discovery-go is missing env var: %v", envVar) 22 | } 23 | return val, nil 24 | } 25 | 26 | // URL finds the specified URL for a service based off of the service's name and which 27 | // interface you are accessing. Values are found in environment variables fitting the scheme: 28 | // SERVICE_{SERVICE NAME}_{INTERFACE NAME}_{PROTO,HOST,PORT}. 29 | func URL(service, name string) (string, error) { 30 | proto, err := Proto(service, name) 31 | if err != nil { 32 | return "", err 33 | } 34 | host, err := Host(service, name) 35 | if err != nil { 36 | return "", err 37 | } 38 | port, err := Port(service, name) 39 | if err != nil { 40 | return "", err 41 | } 42 | 43 | rawURL := fmt.Sprintf("%s://%s:%s", proto, host, port) 44 | u, err := url.Parse(rawURL) 45 | if err != nil { 46 | return "", fmt.Errorf("discovery-go error: %v. Failed to parse URL: %s", err, rawURL) 47 | } 48 | return u.String(), nil 49 | } 50 | 51 | // HostPort finds the specified host:port combo for a service based off of the service's name and 52 | // which interface you are accessing. Values are found in environment variables fitting the scheme: 53 | // SERVICE_{SERVICE NAME}_{INTERFACE NAME}_{PROTO,HOST,PORT}. 54 | func HostPort(service, name string) (string, error) { 55 | host, err := Host(service, name) 56 | if err != nil { 57 | return "", err 58 | } 59 | port, err := Port(service, name) 60 | if err != nil { 61 | return "", err 62 | } 63 | 64 | return net.JoinHostPort(host, port), nil 65 | } 66 | 67 | // ProtoHost finds the specified proto:host combo for a service based off of the service's name and 68 | // which interface you are accessing. Values are found in environment variables fitting the scheme: 69 | // SERVICE_{SERVICE NAME}_{INTERFACE NAME}_{PROTO,HOST,PORT}. 70 | func ProtoHost(service, name string) (string, error) { 71 | proto, err := Proto(service, name) 72 | if err != nil { 73 | return "", err 74 | } 75 | host, err := Host(service, name) 76 | if err != nil { 77 | return "", err 78 | } 79 | 80 | return fmt.Sprintf("%s://%s", proto, host), nil 81 | } 82 | 83 | // Proto finds the specified protocol for a service based off of the service's name and which 84 | // interface you are accessing. Values are found in environment variables fitting the scheme: 85 | // SERVICE_{SERVICE NAME}_{INTERFACE NAME}_PROTO. 86 | func Proto(service, name string) (string, error) { 87 | template := fmt.Sprintf(templateVar, service, name) 88 | return getVar(fmt.Sprintf(template, "PROTO")) 89 | } 90 | 91 | // Host finds the specified host for a service based off of the service's name and which 92 | // interface you are accessing. Values are found in environment variables fitting the scheme: 93 | // SERVICE_{SERVICE NAME}_{INTERFACE NAME}_HOST. 94 | func Host(service, name string) (string, error) { 95 | template := fmt.Sprintf(templateVar, service, name) 96 | return getVar(fmt.Sprintf(template, "HOST")) 97 | } 98 | 99 | // Port finds the specified port for a service based off of the service's name and which 100 | // interface you are accessing. Values are found in environment variables fitting the scheme: 101 | // SERVICE_{SERVICE NAME}_{INTERFACE NAME}_PORT. 102 | func Port(service, name string) (string, error) { 103 | template := fmt.Sprintf(templateVar, service, name) 104 | return getVar(fmt.Sprintf(template, "PORT")) 105 | } 106 | 107 | // ExternalURL finds the specified URL based on the input URL. 108 | // Values are found in environment variables fitting the scheme: 109 | // EXTERNAL_URL_{URL}. 110 | func ExternalURL(inputUrl string) (string, error) { 111 | key := fmt.Sprintf(externalURLVar, strings.ReplaceAll(strings.ToUpper(inputUrl), ".", "_")) 112 | rawUrl, err := getVar(key) 113 | if err != nil { 114 | return "", err 115 | } 116 | u, err := url.Parse(rawUrl) 117 | if err != nil { 118 | return "", fmt.Errorf("discovery-go error: %v. Failed to parse URL: %s", err, rawUrl) 119 | } 120 | return u.String(), nil 121 | } 122 | 123 | func ExternalProtoHost(inputUrl string) (string, error) { 124 | u, err := ExternalURL(inputUrl) 125 | if err != nil { 126 | return "", err 127 | } 128 | return strings.TrimSuffix(u, ":443"), nil 129 | } 130 | -------------------------------------------------------------------------------- /discovery_test.go: -------------------------------------------------------------------------------- 1 | package discovery 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "testing" 7 | ) 8 | 9 | func insertPairs(pairs map[string]string) { 10 | for name, val := range pairs { 11 | err := os.Setenv(name, val) 12 | if err != nil { 13 | log.Fatalf("Failed to set env variable, %s", err) 14 | } 15 | } 16 | } 17 | 18 | func TestMain(m *testing.M) { 19 | insertPairs(map[string]string{ 20 | "SERVICE_REDIS_TCP_PROTO": "tcp", 21 | "SERVICE_REDIS_TCP_HOST": "redis.com", 22 | "SERVICE_REDIS_TCP_PORT": "6379", 23 | 24 | "SERVICE_GOOGLE_API_PROTO": "https", 25 | "SERVICE_GOOGLE_API_HOST": "api.google.com", 26 | "SERVICE_GOOGLE_API_PORT": "80", 27 | 28 | "SERVICE_BREAK_API_HOST": "missing.proto", 29 | "SERVICE_BREAK_API_PORT": "5000", 30 | 31 | "SERVICE_LONG_APP_NAME_API_HOST": "arbitrary", 32 | 33 | "SERVICE_WITH_AUTH_HTTP_PROTO": "https", 34 | "SERVICE_WITH_AUTH_HTTP_HOST": "user:pass@api.google.com", 35 | "SERVICE_WITH_AUTH_HTTP_PORT": "80", 36 | 37 | "EXTERNAL_URL_CLEVER_COM": "https://clever.com:443", 38 | "EXTERNAL_URL_API_CLEVER_COM": "https://api.clever.com:443", 39 | }) 40 | 41 | os.Exit(m.Run()) 42 | } 43 | 44 | func TestTCPDiscovery(t *testing.T) { 45 | expected := "tcp://redis.com:6379" 46 | 47 | url, err := URL("redis", "tcp") 48 | if err != nil { 49 | t.Fatalf("Unexpected error, %s", err) 50 | } else if url != expected { 51 | t.Fatalf("Unexpected result, expected: %s, received: %s", expected, url) 52 | } 53 | } 54 | 55 | func TestURLwithBasicAuth(t *testing.T) { 56 | expected := "https://user:pass@api.google.com:80" 57 | 58 | url, err := URL("with-auth", "http") 59 | if err != nil { 60 | t.Fatalf("Unexpected error, %s", err) 61 | } else if url != expected { 62 | t.Fatalf("Unexpected result, expected: %s, received: %s", expected, url) 63 | } 64 | } 65 | 66 | func TestHTTPSDiscovery(t *testing.T) { 67 | expected := "https://api.google.com:80" 68 | 69 | url, err := URL("google", "api") 70 | if err != nil { 71 | t.Fatalf("Unexpected error, %s", err) 72 | } else if url != expected { 73 | t.Fatalf("Unexpected result, expected: %s, received: %s", expected, url) 74 | } 75 | } 76 | 77 | func TestErrorOnFailure(t *testing.T) { 78 | _, err := URL("break", "api") 79 | if err == nil { 80 | t.Fatalf("Expected error") 81 | } 82 | } 83 | 84 | func TestLongArbitraryNameWithDashes(t *testing.T) { 85 | _, err := Host("long-app-name", "api") 86 | if err != nil { 87 | t.Fatalf("Unexpected error with app name w/ dashes, %s", err) 88 | } 89 | } 90 | 91 | func TestProtoHost(t *testing.T) { 92 | expected := "https://api.google.com" 93 | 94 | protoHost, err := ProtoHost("google", "api") 95 | if err != nil { 96 | t.Fatalf("Unexpected error: %s", err) 97 | } else if protoHost != expected { 98 | t.Fatalf("Unexpected result, expected: %s, received: %s", expected, protoHost) 99 | } 100 | } 101 | 102 | func TestSimpleExternalURL(t *testing.T) { 103 | expected := "https://clever.com:443" 104 | 105 | url, err := ExternalURL("clever.com") 106 | if err != nil { 107 | t.Fatalf("Unexpected error: %s", err) 108 | } else if url != expected { 109 | t.Fatalf("Unexpected result, expected: %s, received: %s", expected, url) 110 | } 111 | } 112 | 113 | func TestComplexExternalURL(t *testing.T) { 114 | expected := "https://api.clever.com:443" 115 | 116 | url, err := ExternalURL("api.clever.com") 117 | if err != nil { 118 | t.Fatalf("Unexpected error: %s", err) 119 | } else if url != expected { 120 | t.Fatalf("Unexpected result, expected: %s, received: %s", expected, url) 121 | } 122 | } 123 | 124 | func TestComplexExternalProtoHost(t *testing.T) { 125 | expected := "https://api.clever.com" 126 | 127 | url, err := ExternalProtoHost("api.clever.com") 128 | if err != nil { 129 | t.Fatalf("Unexpected error: %s", err) 130 | } else if url != expected { 131 | t.Fatalf("Unexpected result, expected: %s, received: %s", expected, url) 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/Clever/discovery-go 2 | 3 | go 1.24 4 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Clever/discovery-go/60caa82a16da3630e9512ebc591a7550601c44cc/go.sum -------------------------------------------------------------------------------- /golang.mk: -------------------------------------------------------------------------------- 1 | # This is the default Clever Golang Makefile. 2 | # It is stored in the dev-handbook repo, github.com/Clever/dev-handbook 3 | # Please do not alter this file directly. 4 | GOLANG_MK_VERSION := 1.3.1 5 | 6 | SHELL := /bin/bash 7 | SYSTEM := $(shell uname -a | cut -d" " -f1 | tr '[:upper:]' '[:lower:]') 8 | .PHONY: golang-test-deps golang-ensure-curl-installed 9 | 10 | # set timezone to UTC for golang to match circle and deploys 11 | export TZ=UTC 12 | 13 | # go build flags for use across all commands which accept them 14 | export GOFLAGS := -mod=vendor $(GOFLAGS) 15 | 16 | # if the gopath includes several directories, use only the first 17 | GOPATH=$(shell echo $$GOPATH | cut -d: -f1) 18 | 19 | # This block checks and confirms that the proper Go toolchain version is installed. 20 | # It uses ^ matching in the semver sense -- you can be ahead by a minor 21 | # version, but not a major version (patch is ignored). 22 | # arg1: golang version 23 | define golang-version-check 24 | _ := $(if \ 25 | $(shell \ 26 | expr >/dev/null \ 27 | `go version | cut -d" " -f3 | cut -c3- | cut -d. -f2 | sed -E 's/beta[0-9]+//'` \ 28 | \>= `echo $(1) | cut -d. -f2` \ 29 | \& \ 30 | `go version | cut -d" " -f3 | cut -c3- | cut -d. -f1` \ 31 | = `echo $(1) | cut -d. -f1` \ 32 | && echo 1), \ 33 | @echo "", \ 34 | $(error must be running Go version ^$(1) - you are running $(shell go version | cut -d" " -f3 | cut -c3-))) 35 | endef 36 | 37 | # FGT is a utility that exits with 1 whenever any stderr/stdout output is recieved. 38 | # We pin its version since its a simple tool that does its job as-is; 39 | # so we're defended against it breaking or changing in the future. 40 | FGT := $(GOPATH)/bin/fgt 41 | $(FGT): 42 | go install -mod=readonly github.com/GeertJohan/fgt@262f7b11eec07dc7b147c44641236f3212fee89d 43 | 44 | golang-ensure-curl-installed: 45 | @command -v curl >/dev/null 2>&1 || { echo >&2 "curl not installed. Please install curl."; exit 1; } 46 | 47 | # Golint is a tool for linting Golang code for common errors. 48 | # We pin its version because an update could add a new lint check which would make 49 | # previously passing tests start failing without changing our code. 50 | # this package is deprecated and frozen 51 | # Infra recommendation is to eventually move to https://github.com/golangci/golangci-lint so don't fail on linting error for now 52 | GOLINT := $(GOPATH)/bin/golint 53 | $(GOLINT): 54 | go install -mod=readonly golang.org/x/lint/golint@738671d3881b9731cc63024d5d88cf28db875626 55 | 56 | # golang-fmt-deps requires the FGT tool for checking output 57 | golang-fmt-deps: $(FGT) 58 | 59 | # golang-fmt checks that all golang files in the pkg are formatted correctly. 60 | # arg1: pkg path 61 | define golang-fmt 62 | @echo "FORMATTING $(1)..." 63 | @PKG_PATH=$$(go list -f '{{.Dir}}' $(1)); $(FGT) gofmt -l=true $${PKG_PATH}/*.go 64 | endef 65 | 66 | # golang-lint-deps requires the golint tool for golang linting. 67 | golang-lint-deps: $(GOLINT) 68 | 69 | # golang-lint calls golint on all golang files in the pkg. 70 | # arg1: pkg path 71 | define golang-lint 72 | @echo "LINTING $(1)..." 73 | @PKG_PATH=$$(go list -f '{{.Dir}}' $(1)); find $${PKG_PATH}/*.go -type f | grep -v gen_ | xargs $(GOLINT) 74 | endef 75 | 76 | # golang-lint-deps-strict requires the golint tool for golang linting. 77 | golang-lint-deps-strict: $(GOLINT) $(FGT) 78 | 79 | # golang-test-deps is here for consistency 80 | golang-test-deps: 81 | 82 | # golang-test uses the Go toolchain to run all tests in the pkg. 83 | # arg1: pkg path 84 | define golang-test 85 | @echo "TESTING $(1)..." 86 | @go test -v $(1) 87 | endef 88 | 89 | # golang-test-strict-deps is here for consistency 90 | golang-test-strict-deps: 91 | 92 | # golang-test-strict uses the Go toolchain to run all tests in the pkg with the race flag 93 | # arg1: pkg path 94 | define golang-test-strict 95 | @echo "TESTING $(1)..." 96 | @go test -v -race $(1) 97 | endef 98 | 99 | # golang-test-strict-cover-deps is here for consistency 100 | golang-test-strict-cover-deps: 101 | 102 | # golang-test-strict-cover uses the Go toolchain to run all tests in the pkg with the race and cover flag. 103 | # appends coverage results to coverage.txt 104 | # arg1: pkg path 105 | define golang-test-strict-cover 106 | @echo "TESTING $(1)..." 107 | @go test -v -race -cover -coverprofile=profile.tmp -covermode=atomic $(1) 108 | @if [ -f profile.tmp ]; then \ 109 | cat profile.tmp | tail -n +2 >> coverage.txt; \ 110 | rm profile.tmp; \ 111 | fi; 112 | endef 113 | 114 | # golang-vet-deps is here for consistency 115 | golang-vet-deps: 116 | 117 | # golang-vet uses the Go toolchain to vet all the pkg for common mistakes. 118 | # arg1: pkg path 119 | define golang-vet 120 | @echo "VETTING $(1)..." 121 | @go vet $(1) 122 | endef 123 | 124 | # golang-test-all-deps installs all dependencies needed for different test cases. 125 | golang-test-all-deps: golang-fmt-deps golang-lint-deps golang-test-deps golang-vet-deps 126 | 127 | # golang-test-all calls fmt, lint, vet and test on the specified pkg. 128 | # arg1: pkg path 129 | define golang-test-all 130 | $(call golang-fmt,$(1)) 131 | $(call golang-lint,$(1)) 132 | $(call golang-vet,$(1)) 133 | $(call golang-test,$(1)) 134 | endef 135 | 136 | # golang-test-all-strict-deps: installs all dependencies needed for different test cases. 137 | golang-test-all-strict-deps: golang-fmt-deps golang-lint-deps-strict golang-test-strict-deps golang-vet-deps 138 | 139 | # golang-test-all-strict calls fmt, lint, vet and test on the specified pkg with strict 140 | # requirements that no errors are thrown while linting. 141 | # arg1: pkg path 142 | define golang-test-all-strict 143 | $(call golang-fmt,$(1)) 144 | $(call golang-lint,$(1)) 145 | $(call golang-vet,$(1)) 146 | $(call golang-test-strict,$(1)) 147 | endef 148 | 149 | # golang-test-all-strict-cover-deps: installs all dependencies needed for different test cases. 150 | golang-test-all-strict-cover-deps: golang-fmt-deps golang-lint-deps-strict golang-test-strict-cover-deps golang-vet-deps 151 | 152 | # golang-test-all-strict-cover calls fmt, lint, vet and test on the specified pkg with strict and cover 153 | # requirements that no errors are thrown while linting. 154 | # arg1: pkg path 155 | define golang-test-all-strict-cover 156 | $(call golang-fmt,$(1)) 157 | $(call golang-lint,$(1)) 158 | $(call golang-vet,$(1)) 159 | $(call golang-test-strict-cover,$(1)) 160 | endef 161 | 162 | # golang-build: builds a golang binary 163 | # arg1: pkg path 164 | # arg2: executable name 165 | define golang-build 166 | @echo "BUILDING $(2)..." 167 | @CGO_ENABLED=0 go build -o bin/$(2) $(1); 168 | endef 169 | 170 | # golang-debug-build: builds a golang binary with debugging capabilities 171 | # arg1: pkg path 172 | # arg2: executable name 173 | define golang-debug-build 174 | @echo "BUILDING $(2) FOR DEBUG..." 175 | @CGO_ENABLED=0 go build -gcflags="all=-N -l" -o bin/$(2) $(1); 176 | endef 177 | 178 | # golang-cgo-build: builds a golang binary with CGO 179 | # arg1: pkg path 180 | # arg2: executable name 181 | define golang-cgo-build 182 | @echo "BUILDING $(2) WITH CGO ..." 183 | @CGO_ENABLED=1 go build -installsuffix cgo -o bin/$(2) $(1); 184 | endef 185 | 186 | # golang-setup-coverage: set up the coverage file 187 | golang-setup-coverage: 188 | @echo "mode: atomic" > coverage.txt 189 | 190 | # golang-update-makefile downloads latest version of golang.mk 191 | golang-update-makefile: 192 | @wget https://raw.githubusercontent.com/Clever/dev-handbook/master/make/golang-v1.mk -O /tmp/golang.mk 2>/dev/null 193 | @if ! grep -q $(GOLANG_MK_VERSION) /tmp/golang.mk; then cp /tmp/golang.mk golang.mk && echo "golang.mk updated"; else echo "golang.mk is up-to-date"; fi 194 | --------------------------------------------------------------------------------