Skip to content

Commit

Permalink
structure the request body following qdm12 suggestion
Browse files Browse the repository at this point in the history
  • Loading branch information
Francesco Calcavecchia committed Jan 2, 2025
1 parent 6f66a08 commit 0b9af33
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 24 deletions.
4 changes: 4 additions & 0 deletions internal/provider/headers/headers.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ func SetXFilter(request *http.Request, value string) {
request.Header.Set("X-Filter", value)
}

func SetXAuthToken(request *http.Request, value string) {
request.Header.Set("X-Auth-Token", value)
}

func SetXAuthUsername(request *http.Request, value string) {
request.Header.Set("X-Auth-Username", value)
}
Expand Down
58 changes: 34 additions & 24 deletions internal/provider/providers/scaleway/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,36 +126,46 @@ func (p *Provider) Update(ctx context.Context, client *http.Client, ip netip.Add
if ip.Is6() {
field_type = "AAAA"
}
requestBody := map[string]interface{}{
"changes": []map[string]interface{}{
{
"set": map[string]interface{}{
"id_fields": map[string]interface{}{
"name": p.field_name,
"type": field_type,
},
"records": []map[string]interface{}{
{
"data": ip.String(),
"ttl": p.ttl,
},
},
},
},
},
}
requestBodyBytes, err := json.Marshal(requestBody)
type recordJSON struct {
Data string `json:"data"`
TTL uint16 `json:"ttl"`
}
type changeJSON struct{
Set struct {
IDFields struct {
Name string `json:"name"`
Type string `json:"type"`
} `json:"id_fields"`
Records []recordJSON `json:"records"`
} `json:"set"`
}
var change changeJSON
change.Set.IDFields.Name = p.field_name
change.Set.IDFields.Type = field_type
change.Set.Records = []recordJSON{{
Data: ip.String(),
TTL: p.ttl,
}}
requestBody := struct {
Changes []changeJSON `json:"changes"`
}{
Changes: []changeJSON{change},
}

buffer := bytes.NewBuffer(nil)
encoder := json.NewEncoder(buffer)
err = encoder.Encode(requestBody)
if err != nil {
return netip.Addr{}, fmt.Errorf("json marshal: %w", err)
return netip.Addr{}, fmt.Errorf("json encoding request body: %w", err)
}

request, err := http.NewRequestWithContext(ctx, http.MethodPatch, u.String(), bytes.NewReader(requestBodyBytes))
request, err := http.NewRequestWithContext(ctx, http.MethodPatch, u.String(), buffer)
if err != nil {
return netip.Addr{}, fmt.Errorf("creating http request: %w", err)
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
request.Header.Set("X-Auth-Token", p.secretKey)
headers.SetContentType(request, "application/json")
headers.SetAccept(request, "application/json")
headers.SetXAuthToken(request, p.secretKey)
headers.SetUserAgent(request)

response, err := client.Do(request)
Expand Down

0 comments on commit 0b9af33

Please sign in to comment.