Merge branch '16265-security-updates' into dependabot/bundler/apps/workbench/loofah...
[arvados.git] / sdk / go / arvadostest / stub.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package arvadostest
6
7 import (
8         "net/http"
9         "net/url"
10
11         "git.arvados.org/arvados.git/sdk/go/arvados"
12 )
13
14 // StubResponse struct with response status and body
15 type StubResponse struct {
16         Status int
17         Body   string
18 }
19
20 // ServerStub with response map of path and StubResponse
21 // Ex:  /arvados/v1/keep_services = arvadostest.StubResponse{200, string(`{}`)}
22 type ServerStub struct {
23         Responses map[string]StubResponse
24 }
25
26 func (stub *ServerStub) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
27         if req.URL.Path == "/redirect-loop" {
28                 http.Redirect(resp, req, "/redirect-loop", http.StatusFound)
29                 return
30         }
31
32         pathResponse := stub.Responses[req.URL.Path]
33         if pathResponse.Status == -1 {
34                 http.Redirect(resp, req, "/redirect-loop", http.StatusFound)
35         } else if pathResponse.Body != "" {
36                 resp.WriteHeader(pathResponse.Status)
37                 resp.Write([]byte(pathResponse.Body))
38         } else {
39                 resp.WriteHeader(500)
40                 resp.Write([]byte(``))
41         }
42 }
43
44 // SetServiceURL overrides the given service config/discovery with the
45 // given internalURLs.
46 //
47 // ExternalURL is set to the last internalURL, which only aims to
48 // address the case where there is only one.
49 //
50 // SetServiceURL panics on errors.
51 func SetServiceURL(service *arvados.Service, internalURLs ...string) {
52         service.InternalURLs = map[arvados.URL]arvados.ServiceInstance{}
53         for _, u := range internalURLs {
54                 u, err := url.Parse(u)
55                 if err != nil {
56                         panic(err)
57                 }
58                 service.InternalURLs[arvados.URL(*u)] = arvados.ServiceInstance{}
59                 service.ExternalURL = arvados.URL(*u)
60         }
61 }