Skip to content

Instantly share code, notes, and snippets.

@Solution
Created December 13, 2018 21:32
Show Gist options
  • Save Solution/724de563e423a1739fe50dc674110af1 to your computer and use it in GitHub Desktop.
Save Solution/724de563e423a1739fe50dc674110af1 to your computer and use it in GitHub Desktop.
Simple request factory
package client
import (
"net/http"
"strings"
"github.com/pkg/errors"
)
type RequestFactory struct {
schema Schema
baseHostName string
basePath string
version string
authToken string
}
func CreateRequestFactory(baseHostName string, basePath string, version string) (*RequestFactory, error) {
if len(baseHostName) == 0 {
return nil, errors.New("Base host name must be defined in request factory")
}
return &RequestFactory{
schema: HTTP,
baseHostName: baseHostName,
basePath: basePath,
version: version,
}, nil
}
func (rg *RequestFactory) Create(method Method, path string, params map[string]string, body string) *http.Request {
req, _ := http.NewRequest(string(method), rg.buildPath(path), strings.NewReader(body))
req.Header.Add("Content-type", "application/json")
u := req.URL
u.Scheme = string(rg.schema)
u.Host = rg.baseHostName
// method detection
// parameters building
// post body building and so on
return req
}
func (rg *RequestFactory) SetAuthToken(authToken string) *RequestFactory{
rg.authToken = authToken
return rg
}
func (rg *RequestFactory) HasAuthToken() bool {
return rg.authToken != ""
}
func (rg *RequestFactory) buildPath(path string) string {
builder := strings.Builder{}
builder.WriteString("/")
if rg.version != "" {
builder.WriteString(rg.version)
builder.WriteString("/")
}
builder.WriteString(rg.basePath)
if len(rg.basePath) > 0 && rg.basePath[len(rg.basePath) - 1:] != "/" {
builder.WriteString("/")
}
builder.WriteString(path)
return builder.String()
}
// default is http, you can switch by some boolean param
func (rg *RequestFactory) UseHttps() {
rg.schema = HTTPS
}
// appending simple bearer token
func (rg *RequestFactory) appendAuthToken(r *http.Request, authToken string) *http.Request {
r.Header.Add("Authorization", "Bearer " + authToken)
return r
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment