Last active
December 19, 2022 03:48
-
-
Save maxclav/b982bfd7da5f4aa9f03bb5877c02b958 to your computer and use it in GitHub Desktop.
Builder Design Pattern example in Go (GoLang).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another good example:
https://github.com/tmrts/go-patterns/blob/master/creational/builder.md