apollo-backend/internal/reddit/request.go

93 lines
1.7 KiB
Go
Raw Normal View History

2021-05-10 00:51:15 +00:00
package reddit
import (
"encoding/base64"
"fmt"
"net/http"
"net/url"
"strings"
)
2021-07-12 20:27:59 +00:00
const userAgent = "server:apollo-backend:v1.0 (by /u/iamthatis)"
2021-05-10 00:51:15 +00:00
type Request struct {
body url.Values
2021-06-24 02:19:43 +00:00
query url.Values
2021-05-10 00:51:15 +00:00
method string
token string
url string
auth string
2021-07-08 23:26:15 +00:00
tags []string
2021-05-10 00:51:15 +00:00
}
type RequestOption func(*Request)
func NewRequest(opts ...RequestOption) *Request {
2021-07-08 23:26:15 +00:00
req := &Request{url.Values{}, url.Values{}, "GET", "", "", "", nil}
2021-05-10 00:51:15 +00:00
for _, opt := range opts {
opt(req)
}
return req
}
func (r *Request) HTTPRequest() (*http.Request, error) {
req, err := http.NewRequest(r.method, r.url, strings.NewReader(r.body.Encode()))
2021-06-24 02:19:43 +00:00
req.URL.RawQuery = r.query.Encode()
2021-05-10 00:51:15 +00:00
req.Header.Add("User-Agent", userAgent)
if r.token != "" {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", r.token))
}
if r.auth != "" {
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", r.auth))
}
return req, err
}
2021-07-08 23:26:15 +00:00
func WithTags(tags []string) RequestOption {
return func(req *Request) {
req.tags = tags
}
}
2021-05-10 00:51:15 +00:00
func WithMethod(method string) RequestOption {
return func(req *Request) {
req.method = method
}
}
func WithURL(url string) RequestOption {
return func(req *Request) {
req.url = url
}
}
func WithBasicAuth(user, password string) RequestOption {
return func(req *Request) {
encoded := base64.StdEncoding.EncodeToString([]byte(user + ":" + password))
req.auth = encoded
}
}
func WithToken(token string) RequestOption {
return func(req *Request) {
req.token = token
}
}
func WithBody(key, val string) RequestOption {
return func(req *Request) {
req.body.Set(key, val)
}
}
2021-06-24 02:19:43 +00:00
func WithQuery(key, val string) RequestOption {
return func(req *Request) {
req.query.Set(key, val)
}
}