Skip to content

Instantly share code, notes, and snippets.

@mqnoy
Created June 4, 2024 04:27
Show Gist options
  • Save mqnoy/3fe31935f9a9a931705839242fb09795 to your computer and use it in GitHub Desktop.
Save mqnoy/3fe31935f9a9a931705839242fb09795 to your computer and use it in GitHub Desktop.
http client go
package httprq
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
"sync"
"time"
)
var (
once sync.Once
HttpRQClient *HttpRQ
)
type HttpRQ struct {
BaseURL string
Client http.Client
headers map[string]string
}
func (h *HttpRQ) SetBaseURL(url string) *HttpRQ {
h.BaseURL = url
return h
}
func (h *HttpRQ) SetHeaders(headers map[string]string) *HttpRQ {
h.headers = headers
return h
}
func (h *HttpRQ) Get(urlPath string, result interface{}) error {
url := h.createUrl(urlPath)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return err
}
// Add custom headers
for key, value := range h.headers {
req.Header.Add(key, value)
}
// Perform the request
resp, err := h.Client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// Decode the response
err = json.NewDecoder(resp.Body).Decode(result)
if err != nil {
return err
}
return nil
}
func (h *HttpRQ) Post(urlPath string, payload interface{}, result interface{}) error {
payloadBytes, err := json.Marshal(payload)
if err != nil {
return err
}
url := h.createUrl(urlPath)
req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(payloadBytes))
if err != nil {
return err
}
// Add custom headers
for key, value := range h.headers {
req.Header.Add(key, value)
}
// Perform the request
resp, err := h.Client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// Decode the response
err = json.NewDecoder(resp.Body).Decode(result)
if err != nil {
return err
}
return nil
}
func (h *HttpRQ) createUrl(urlPath string) string {
url, err := url.JoinPath(h.BaseURL, urlPath)
if err != nil {
panic(err)
}
return url
}
func init() {
once.Do(func() {
HttpRQClient = &HttpRQ{
Client: http.Client{
Timeout: time.Second * 10,
Transport: &loggingTransport{},
},
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment