1// +build go1.13
2
3// Copyright 2017 Microsoft Corporation. All rights reserved.
4// Use of this source code is governed by an MIT
5// license that can be found in the LICENSE file.
6
7package azcore_test
8
9import (
10	"context"
11	"encoding/json"
12	"fmt"
13	"io/ioutil"
14	"log"
15	"net/http"
16	"strings"
17
18	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
19)
20
21func ExamplePipeline_Do() {
22	req, err := azcore.NewRequest(context.Background(), http.MethodGet, "https://github.com/robots.txt")
23	if err != nil {
24		log.Fatal(err)
25	}
26	pipeline := azcore.NewPipeline(nil)
27	resp, err := pipeline.Do(req)
28	if err != nil {
29		log.Fatal(err)
30	}
31	robots, err := ioutil.ReadAll(resp.Body)
32	resp.Body.Close()
33	if err != nil {
34		log.Fatal(err)
35	}
36	fmt.Printf("%s", robots)
37}
38
39func ExampleRequest_SetBody() {
40	req, err := azcore.NewRequest(context.Background(), http.MethodPut, "https://contoso.com/some/endpoint")
41	if err != nil {
42		log.Fatal(err)
43	}
44	body := strings.NewReader("this is seekable content to be uploaded")
45	err = req.SetBody(azcore.NopCloser(body), "text/plain")
46	if err != nil {
47		log.Fatal(err)
48	}
49}
50
51func ExampleLogger_Should() {
52	// you can create your own logging classification as needed
53	const LogExpensiveThing azcore.LogClassification = "ExpensiveThing"
54	if azcore.Log().Should(LogExpensiveThing) {
55		// perform expensive calculation only when enabled
56		azcore.Log().Write(LogExpensiveThing, "expensive log message")
57	}
58}
59
60func ExampleLogger_SetClassifications() {
61	// only log HTTP requests and responses
62	azcore.Log().SetClassifications(azcore.LogRequest, azcore.LogResponse)
63}
64
65func ExampleLogger_SetListener() {
66	// a simple logger that writes to stdout
67	azcore.Log().SetListener(func(cls azcore.LogClassification, msg string) {
68		fmt.Printf("%s: %s\n", cls, msg)
69	})
70}
71
72type Widget struct {
73	Name  *string `json:",omitempty"`
74	Count *int    `json:",omitempty"`
75}
76
77func (w Widget) MarshalJSON() ([]byte, error) {
78	msg := map[string]interface{}{}
79	if azcore.IsNullValue(w.Name) {
80		msg["name"] = nil
81	} else if w.Name != nil {
82		msg["name"] = w.Name
83	}
84	if azcore.IsNullValue(w.Count) {
85		msg["count"] = nil
86	} else if w.Count != nil {
87		msg["count"] = w.Count
88	}
89	return json.Marshal(msg)
90}
91
92func ExampleNullValue() {
93	w := Widget{
94		Count: azcore.NullValue(0).(*int),
95	}
96	b, _ := json.Marshal(w)
97	fmt.Println(string(b))
98	// Output:
99	// {"count":null}
100}
101