-
Notifications
You must be signed in to change notification settings - Fork 10
/
httpClient.go
96 lines (89 loc) · 2.57 KB
/
httpClient.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
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
)
//=========================================================================================
func main() {
// two different ways to execute an http.GET
doGet("http://cnn.com/")
fmt.Println("")
doGetClient("http://cnn.com/")
/**
* this does an minimal http.PUT
* you might have to add a "Content-Type: some value"
* to the request header if you put to a different system
* or put a different file type
**/
// replace this url with your PUT enabled restful web server
doPut("http://localhost:8080/exist/rest/db/eric/golang.xml")
/** for reference the url above is for an exist-db instance
* to find out more visit http://exist-db.org/
**/
}
//=========================================================================================
func doGet(url string) {
response, err := http.Get(url)
if err != nil {
log.Fatal(err)
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println("The calculated length is:", len(string(contents)), "for the url:", url)
fmt.Println(" ", response.StatusCode)
hdr := response.Header
for key, value := range hdr {
fmt.Println(" ", key, ":", value)
}
}
}
//=========================================================================================
func doGetClient(url string) {
client := &http.Client{}
response, err := client.Get(url)
if err != nil {
log.Fatal(err)
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println("The calculated length is:", len(string(contents)), "for the url:", url)
fmt.Println(" ", response.StatusCode)
hdr := response.Header
for key, value := range hdr {
fmt.Println(" ", key, ":", value)
}
}
}
//=========================================================================================
func doPut(url string) {
client := &http.Client{}
request, err := http.NewRequest("PUT", url, strings.NewReader("<golang>really</golang>"))
request.SetBasicAuth("admin", "admin")
request.ContentLength = 23
response, err := client.Do(request)
if err != nil {
log.Fatal(err)
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println("The calculated length is:", len(string(contents)), "for the url:", url)
fmt.Println(" ", response.StatusCode)
hdr := response.Header
for key, value := range hdr {
fmt.Println(" ", key, ":", value)
}
fmt.Println(contents)
}
}