Some checks failed
CI / Run lints and checks (push) Failing after 47s
CI / Run tests (push) Failing after 1s
CI / Run race tests (push) Failing after 5s
CI / Build CLI docs (push) Has been skipped
CI / Run buf actions (push) Failing after 5s
CodeQL / Analyze (go) (push) Failing after 3s
CodeQL / Analyze (javascript) (push) Failing after 2s
Docker Image Scanners / scanners (push) Failing after 3s
Format / format (push) Failing after 3s
Synchronize Issue Labels / Synchronize Issue Labels (push) Has been skipped
CI / Generate release (push) Has been skipped
CI / Draft newsletter (push) Has been skipped
CI / Pending approval Slack notification (push) Has been skipped
CI / Send newsletter (push) Has been skipped
52 lines
1.3 KiB
Go
52 lines
1.3 KiB
Go
// Copyright © 2023 Ory Corp
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
package httpx
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
// NewRequestJSON returns a new JSON *http.Request.
|
|
func NewRequestJSON(method, url string, data interface{}) (*http.Request, error) {
|
|
var b bytes.Buffer
|
|
if err := json.NewEncoder(&b).Encode(data); err != nil {
|
|
return nil, errors.WithStack(err)
|
|
}
|
|
req, err := http.NewRequest(method, url, &b)
|
|
if err != nil {
|
|
return nil, errors.WithStack(err)
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
return req, nil
|
|
}
|
|
|
|
// NewRequestForm returns a new POST Form *http.Request.
|
|
func NewRequestForm(method, url string, data url.Values) (*http.Request, error) {
|
|
req, err := http.NewRequest(method, url, strings.NewReader(data.Encode()))
|
|
if err != nil {
|
|
return nil, errors.WithStack(err)
|
|
}
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
return req, nil
|
|
}
|
|
|
|
// MustNewRequest returns a new *http.Request or fatals.
|
|
func MustNewRequest(method, url string, body io.Reader, contentType string) *http.Request {
|
|
req, err := http.NewRequest(method, url, body)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if contentType != "" {
|
|
req.Header.Set("Content-Type", contentType)
|
|
}
|
|
return req
|
|
}
|