Skip to content

Instantly share code, notes, and snippets.

@maxclav
Last active December 19, 2022 03:48
Show Gist options
  • Save maxclav/b982bfd7da5f4aa9f03bb5877c02b958 to your computer and use it in GitHub Desktop.
Save maxclav/b982bfd7da5f4aa9f03bb5877c02b958 to your computer and use it in GitHub Desktop.
Builder Design Pattern example in Go (GoLang).
package httprequest
import (
"context"
"fmt"
"io"
"net/http"
)
// You will need a builder pattern
// only if "building" the resource might return an error.
// If it doesnt, you can simply create methods to your struct
// that will override it's default values.
func NewBuilder(url string) Builder {
return &builder{
headers: map[string][]string{},
url: url,
body: nil,
method: http.MethodGet,
ctx: context.Background(),
close: false,
}
}
type Builder interface {
Method(method string) Builder
Body(r io.Reader) Builder
AddHeader(name, value string) Builder
Close(close bool) Builder
Build() (*http.Request, error)
}
type builder struct {
headers map[string][]string
url string
method string
body io.Reader
close bool
ctx context.Context
}
func (b *builder) Method(method string) Builder {
b.method = method
return b
}
func (b *builder) Body(r io.Reader) Builder {
b.body = r
return b
}
func (b *builder) AddHeader(name, value string) Builder {
values, found := b.headers[name]
if !found {
values = make([]string, 0, 10)
}
b.headers[name] = append(values, value)
return b
}
func (b *builder) Close(close bool) Builder {
b.close = close
return b
}
func (b *builder) Build() (*http.Request, error) {
req, err := http.NewRequestWithContext(b.ctx, b.method, b.url, b.body)
if err != nil {
return nil, err
}
for key, values := range b.headers {
for _, value := range values {
req.Header.Add(key, value)
}
}
req.Close = b.close
return req, nil
}
@maxclav
Copy link
Author

maxclav commented Dec 19, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment