Context
Using Go context with SP client
Gosip client respects native Go Context, you can pass a context on a low level or to a Fluent API to control requests's deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.

Low level client

On the low level dealing with the contexts is identical to native approach:
1
client := &gosip.SPClient{AuthCnfg: auth}
2
3
var req *http.Request
4
// Initiate API request
5
// ...
6
7
req = req.WithContext(context.Background()) // <- pass a context
8
9
resp, err := client.Execute(req)
10
if err != nil {
11
fmt.Printf("Unable to request api: %v", err)
12
return
13
}
Copied!

HTTP Client

While using HTTPClient, context is defined together with request config.
1
spClient := api.NewHTTPClient(&gosip.SPClient{AuthCnfg: auth})
2
3
endpoint := auth.GetSiteURL() + "/_api/web?$select=Title"
4
5
reqConf := &api.RequestConfig{
6
Context: context.Background(), // <- pass a context
7
}
8
9
data, err := spClient.Get(endpoint, reqConf)
10
if err != nil {
11
log.Fatalf("%v\n", err)
12
}
13
14
// spClient.Post(endpoint, body, reqConf) // generic POST
15
16
// generic DELETE helper crafts "X-Http-Method"="DELETE" header
17
// spClient.Delete(endpoint, reqConf)
18
19
// generic UPDATE helper crafts "X-Http-Method"="MERGE" header
20
// spClient.Update(endpoint, body, reqConf)
21
22
// CSOM helper (client.svc/ProcessQuery)
23
// spClient.ProcessQuery(endpoint, body, reqConf)
Copied!

Fluent API

With Fluent API, context is managed in the same way as in the previous example with the only difference how it is chained to fluent syntax.
1
config := &api.RequestConfig{
2
Context: context.Background(), // <- pass a context
3
}
4
5
sp := api.NewSP(client).Conf(config)
6
7
data, err := sp.Web().Lists().Select("Id,Title").Get()
8
if err != nil {
9
log.Fatalln(err)
10
}
Copied!
Conf method can be used almost on any hierarchy level. It's inherited with capability to redefine.
Last modified 1yr ago
Export as PDF
Copy link