This repository has been archived by the owner on Feb 7, 2024. It is now read-only.
/
remote_api.go
85 lines (76 loc) · 1.91 KB
/
remote_api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright 2014 Ronoaldo JLP <ronoaldo@gmail.com>
// Licensed under the Apache License, Version 2.0
package main
import (
"log"
"net/http"
"net/http/httputil"
"golang.org/x/net/context"
"golang.org/x/oauth2/google"
)
var remoteAPIScopes = []string{
"https://www.googleapis.com/auth/appengine.apis",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/cloud.platform",
}
func newClient() (*http.Client, error) {
log.Printf("Connecting with %s:%s ...", host, port)
if host == "localhost" || host == "127.0.0.1" {
log.Printf("Using a local connection ...")
hc := &http.Client{
Transport: &transport{http.DefaultTransport},
}
return hc, nil
}
log.Printf("Autodetecting credentials do use ...")
hc, err := google.DefaultClient(context.Background(), remoteAPIScopes...)
if hc != nil {
hc.Transport = &transport{hc.Transport}
}
return hc, err
}
type transport struct {
Wrapped http.RoundTripper
}
func (t *transport) RoundTrip(r *http.Request) (*http.Response, error) {
if debug {
log.Printf("Performing request to %s ...", r.URL)
}
if r.URL.Host == "localhost" || r.URL.Host == "127.0.0.1" {
r.URL.Host = "localhost:" + port
r.URL.Scheme = "http"
r.AddCookie(&http.Cookie{
Name: "dev_appserver_login",
Value: "admin@example.com:True:123076125137242107209",
Path: "/",
Domain: r.URL.Host,
})
}
resp, err := t.Wrapped.RoundTrip(r)
debugRequest(r)
debugResponse(resp)
if debug {
log.Print("Request finished\n")
}
return resp, err
}
func debugRequest(r *http.Request) *http.Request {
if debug {
b, err := httputil.DumpRequest(r, false)
if err != nil {
log.Printf(err.Error())
}
log.Print("Request: \n", string(b))
}
return r
}
func debugResponse(r *http.Response) *http.Response {
if debug {
b, err := httputil.DumpResponse(r, false)
if err != nil {
log.Printf(err.Error())
}
log.Print("Response: \n", string(b))
}
return r
}