-
Notifications
You must be signed in to change notification settings - Fork 7
Description
Hi guys and thanks for this great SDK, I'm loving using Datastart with Go!
I found out there is a Get/Post/etcSSE helper function to build the @post('url') string, which I find useful to avoid typos. In practice, I was limited by the fact that it only allows to build the url inside the single quotes.
That means I can't use it if I want to add options @post('url', { contentType: 'form' }).
Following the implementation of PatchElements, I was thinking of an implementation like this, that would have type safety and autocompletion:
package main
import (
"fmt"
"strings"
)
func main() {
s := PostSSE("/endpoint", WithContentType("form"), WithOpenWhenHidden(true))
fmt.Println(s)
}
type PostSSEOptions struct {
ContentType string
OpenWhenHidden bool
}
type PostSSEOption func(o *PostSSEOptions)
func WithContentType(contentType string) PostSSEOption {
return func(o *PostSSEOptions) {
o.ContentType = contentType
}
}
func WithOpenWhenHidden(openWhenHidden bool) PostSSEOption {
return func(o *PostSSEOptions) {
o.OpenWhenHidden = openWhenHidden
}
}
func PostSSE(url string, opts ...PostSSEOption) string {
if len(opts) == 0 {
return fmt.Sprintf("@post('%s')", url)
}
options := &PostSSEOptions{
ContentType: "",
OpenWhenHidden: false,
}
for _, opt := range opts {
opt(options)
}
result := fmt.Sprintf("@post('%s',{", url)
items := []string{}
if options.ContentType != "" {
items = append(items, fmt.Sprintf("contentType:'%s'", options.ContentType))
}
if options.OpenWhenHidden {
items = append(items, "openWhenHidden:true")
}
optsStr := strings.Join(items, ",")
result += optsStr + "})"
return result
}Here is a playground: https://goplay.tools/snippet/MMYkwIxRIyV
Unfortunately, that would be a breaking change. Also, maybe you prefer let the user define those functions so it wouldn't be a burden to maintain for futur iterations of Datastar.
I would be happy to contribute of course if you confirm a prefered way to do this! I have no idea how to build strings efficiently.
What do you think ?