♻️ Add custom http functions so that User-Agent is always sent

This commit is contained in:
Dan Jones 2023-09-24 15:26:26 -05:00
commit 2208b1de55
3 changed files with 62 additions and 15 deletions

54
utils/http/http.go Normal file
View file

@ -0,0 +1,54 @@
package http
import (
"io"
h "net/http"
u "net/url"
"strings"
"codeberg.org/danjones000/strip-beats/config"
)
func addUserAgent(req *h.Request) {
req.Header.Set("User-Agent", config.UserAgent)
}
func NewRequest(method, url string, body io.Reader) (*h.Request, error) {
req, err := h.NewRequest(method, url, body)
if err != nil {
return nil, err
}
addUserAgent(req)
return req, nil
}
func Do(req *h.Request) (*h.Response, error) {
addUserAgent(req)
return h.DefaultClient.Do(req)
}
func GetWithQuery(url string, query u.Values) (*h.Response, error) {
req, err := h.NewRequest(h.MethodGet, url, nil)
if err != nil {
return nil, err
}
q := req.URL.Query()
for k, vs := range query {
for _, v := range vs {
q.Add(k, v)
}
}
req.URL.RawQuery = q.Encode()
return Do(req)
}
func PostForm(url string, form u.Values) (*h.Response, error) {
body := strings.NewReader(form.Encode())
req, err := h.NewRequest(h.MethodPost, url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return Do(req)
}