A simple request (http.Request) builder for Golang.
import "github.com/juanenmellare/gorequestbuilder"
In every request buillder set the HTTP method and the base URL otherwise it'll return a nil request and an error.
request, err := gorequestbuilder.NewRequestBuilder().
SetMethodGet().
SetBaseURL("https://en.wikipedia.org").
SetPath("/wiki/Go_(programming_language)").
Build()
var requestBuilder = gorequestbuilder.NewRequestBuilder()
requestBuilder.AddHeader("Authorization", "Basic R29sYW5nIERldmVsb3Blcg==")
var requestBuilder = gorequestbuilder.NewRequestBuilder()
requestBuilder.AddQueryParameter("query", "language=golang")
type Body struct {
Message string `json:"message"`
}
body := &Body{
Message: "Golang is awesome!",
}
var requestBuilder = gorequestbuilder.NewRequestBuilder()
requestBuilder.SetMethodPost().SetBody(body)
var requestBuilder = gorequestbuilder.NewRequestBuilder()
.
.
.
request, err = requestBuilder.Build()
package main
import (
"errors"
"fmt"
"github.com/juanenmellare/gorequestbuilder"
"io/ioutil"
"net/http"
)
type RestClient interface {
Call(requestBuilder gorequestbuilder.RequestBuilder) (*http.Response, error)
}
type restClientImpl struct {
baseURL string
client *http.Client
}
func NewRestClient(baseURL string, client *http.Client) RestClient {
return &restClientImpl{
baseURL: baseURL,
client: client,
}
}
func (r restClientImpl) Call(requestBuilder gorequestbuilder.RequestBuilder) (*http.Response, error) {
request, err := requestBuilder.SetBaseURL(r.baseURL).Build()
if err != nil {
return nil, errors.New("Build request error: " + err.Error())
}
return r.client.Do(request)
}
func main() {
restClient := NewRestClient("http://0.0.0.0:8080", &http.Client{})
requestBuilder := gorequestbuilder.NewRequestBuilder().SetMethodGet().SetPath("/v1/foo")
response, err := restClient.Call(requestBuilder)
if err != nil {
fmt.Println("Error while trying to call from rest client: " + err.Error())
return
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
fmt.Println("[status: " + response.Status + "] - [body: " + string(body) + "]")
}