gosvelt

package module
v1.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 22, 2024 License: MIT Imports: 26 Imported by: 0

README

GoSvelt

The fasthttp fullstack golang framwork using svelte (support tailwindcss) that use to be (blazingly) faster than default sveltekit

Why GoSvelt ?

Fullstack integration of Svelte

Yeah, gosvelt will compile, group, and serve svelte pages at runtime which is pretty cool.
We are using the vitejs/vite svelte typescript compiler, with this, we can do likely everything we want, we could add few really interesting options.
The "compiler" accept for the moment javascript / typescript svelte and tailwindcss, if you want some features to be added, i'll be happy to add them.
A Svelte handler will give you a svelte map wich contain "js" and "css" URLs, you can add to this map your own attributes that will be rendered on the html template (Note: if you add for example a "test" element to the map, you have to add the &{test} element in the html template)

func main() {
	app := gosvelt.New()

	app.Svelte("/", "App.svelte",
		func(c *gs.Context, svelte gs.Map) error {
			return c.Html(200, "assets/index.html", svelte)
		},
		gs.WithPackageManager("pnpm"),
		gs.WithTailwindcss,
		gs.WithRoot("views"),
	)

	app.Start(":80")
}

You can note that this could be faster (blazingly fast) than default sveltekit or default vite server as go is likely way faster than nodejs.

Cool way to do SSE

There are actually two way to use sse in gosvelt:

  • The context way where you can instantiate your channels in the handler function and you can return a goroutine that will handle the sse stream.
  • The handler way wich is a handler that will take outside channels (it could be really nice if you have some external struct for events handling) and instead of giving a handler function, you just give the goroutine function that will handle the sse stream.
func main() {
	app := gosvelt.New()

	app.Get("/sse", func(c *gs.Context) error {
		datach := make(chan interface{})
		closech := make(chan struct{})

		return c.Sse(datach, closech, func() {
			defer close(closech)
			datach <- "hello world"

			for i := 0; i < 6; i++ {
				time.Sleep(200 * time.Millisecond)
				datach <- gs.SseEvent{
					Name: "date",
					Data: fmt.Sprintf("time: %v", time.Now()),
				}
			}
		})
	})

	datach := make(chan interface{})
	closech := make(chan struct{})

	app.Sse("/ssetoo", datach, closech, func() {
		defer close(closech)
		datach <- "hello world"

		for i := 0; i < 6; i++ {
			time.Sleep(200 * time.Millisecond)
			datach <- gs.SseEvent{
				Name: "date",
				Data: fmt.Sprintf("time: %v", time.Now()),
			}
		}
	})

	app.Start(":80")
}
Pretty simple syntax

The syntax is really easy to remember / use if you are beggining with golang framworks and if you already know all this (useless) framworking stuff, it's like most popular framworks (fiber, gin, echo, ...) so you won't be lost!

func main() {
	app := gosvelt.New(
		gs.WithHttp2,
	)

	app.Get("/gg/:name", func(c *gosvelt.Context) error { // url params
		return c.Json(200, gosvelt.Map{"gg": c.Param("name")})
	})

	app.Get("/ws", func(c *gosvelt.Context) error { // websocket handler
		return c.Ws(func(conn *websocket.Conn) {
			conn.WriteJSON(gosvelt.Map{"ez": "pz"})
		})
	})

	app.Static("/index", "assets/index.html") // static files

	app.Svelte("/", "views/App.svelte", // svelte page handler (runtime compiled)
		func(c *gs.Context, svelte gs.Map) error {
			return c.Html(200, "assets/index.html", svelte)
		},
	)

	app.Start(":80")
}

Todo:

  • error handler panic issue
  • new gosvelt config options
  • live reload
  • template and init util (with gitdl)
  • CSR (Client Side Rendering)
  • SSR (Server Side Rendering)
  • ISR (Incremental Static Regeneration)
  • SSE (Server Sent Events)
  • WS (Web Socket)
  • CSS Engine (Tailwindcss)
  • Add layout system

Documentation

Index

Constants

View Source
const (
	CharsetUTF8 = "charset=UTF-8"

	// Methods
	MGet     = http.MethodGet     // get
	MPost    = http.MethodPost    // post
	MPut     = http.MethodPut     // put
	MDelete  = http.MethodDelete  // delete
	MConnect = http.MethodConnect // connect
	MOptions = http.MethodOptions // options

	// Mime
	MAppJSON       = "application/json"                  // json
	MAppProto      = "application/protobuf"              // protobuf
	MAppJS         = "application/javascript"            // js
	MAppXML        = "application/xml"                   // xml
	MAppForm       = "application/x-www-form-urlencoded" // form
	MOctStream     = "application/octet-stream"          // octet stream
	MTextPlain     = "text/plain"                        // text
	MTextHTML      = "text/html"                         // html
	MTextXML       = "text/xml"                          // xml text
	MAppJsonUTF8   = MAppJSON + "; " + CharsetUTF8       // json utf8
	MAppJsUTF8     = MAppJS + "; " + CharsetUTF8         // js utf8
	MAppXmlUTF8    = MAppXML + "; " + CharsetUTF8        // xml utf8
	MTextPlainUTF8 = MTextPlain + "; " + CharsetUTF8     // text utf8
	MTextHtmlUTF8  = MTextHTML + "; " + CharsetUTF8      // html utf8
	MTextXmlUTF8   = MTextXML + "; " + CharsetUTF8       // xml text utf8
)

Variables

View Source
var (
	WithLog = func(o *Options) {
		o.log = true
	}
	WithHttp2 = func(o *Options) {
		o.http2 = true
	}
	WithErrorHandler = func(errorHandler ErrorHandlerFunc) Option {
		return func(o *Options) {
			o.errorHandler = errorHandler
		}
	}
	WithTailwind = func(tailwindConfig string) Option {
		return func(o *Options) {
			o.tailwindcssCfg = &tailwindConfig
		}
	}
	WithPostcss = func(postcssConfig string) Option {
		return func(o *Options) {
			o.postcssCfg = &postcssConfig
		}
	}
)
View Source
var (
	WithTailwindcss = func(o *SvelteOptions) {
		o.tailwindcss = true
	}
	WithPackageManager = func(packageManager string) SvelteOption {
		return func(o *SvelteOptions) {
			o.packageManager = packageManager
		}
	}
	WithRoot = func(rootFolder string) SvelteOption {
		return func(o *SvelteOptions) {
			o.rootFolder = &rootFolder
		}
	}
)

Functions

func BuildSvelte added in v1.4.0

func BuildSvelte(inputSvelteFile string, options ...SvelteOption) (string, string, error)

Types

type Context

type Context struct {
	Ctx context.Context
	// contains filtered or unexported fields
}

func (*Context) Args

func (c *Context) Args() *fasthttp.Args

func (*Context) Blob

func (c *Context) Blob(code int, b []byte) error

return bytes datas to client

func (*Context) CDel

func (c *Context) CDel(key string)

func (*Context) CGet

func (c *Context) CGet(key string) string

func (*Context) CReset

func (c *Context) CReset()

func (*Context) CSet

func (c *Context) CSet(key, value string)

func (*Context) Cookie

func (c *Context) Cookie(key string) string

get the page cookies with key

func (*Context) File

func (c *Context) File(code int, file string, compress ...bool) error

func (*Context) GetForm added in v1.3.0

func (c *Context) GetForm(key string) []byte

func (*Context) Html

func (c *Context) Html(code int, t string, args ...any) error

func (*Context) Json

func (c *Context) Json(code int, j interface{}) error

return json datas to client

func (*Context) Method

func (c *Context) Method() string

func (*Context) Param

func (c *Context) Param(key interface{}) interface{}

get the url params with key

func (*Context) Path

func (c *Context) Path() string

func (*Context) Proto

func (c *Context) Proto(code int, p proto.Message) error

return proto datas to client

func (*Context) Protocol

func (c *Context) Protocol() string

get the protocol of the request

func (*Context) Redirect

func (c *Context) Redirect(code int, url string) error

func (*Context) Req

func (c *Context) Req() *fasthttp.Request

func (*Context) Res

func (c *Context) Res() *fasthttp.Response

func (*Context) Secure

func (c *Context) Secure() bool

true if request is secure by https

func (*Context) SetCType

func (c *Context) SetCType(ctype string)

set response content type

func (*Context) SetCookie

func (c *Context) SetCookie(k, v string, expire time.Time)

add an cookie

func (*Context) SetHeader

func (c *Context) SetHeader(key, value string)

set response header

func (*Context) SetStatusCode

func (c *Context) SetStatusCode(code int)

set response status code in int

func (*Context) Sse added in v1.3.0

func (c *Context) Sse(datach chan interface{}, closech chan struct{}, fn func()) error

func (*Context) Text

func (c *Context) Text(code int, t string) error

return text datas to client

func (*Context) Write

func (c *Context) Write(body []byte)

write to client

func (*Context) Ws

func (c *Context) Ws(handler websocket.FastHTTPHandler) error

return ws connection NOTE: this need websocket.FastHTTPHandler handler and all ws code will be in the arg handler

type ErrorHandlerFunc

type ErrorHandlerFunc func(c *fasthttp.RequestCtx, err error)

type GoSvelt

type GoSvelt struct {
	// contains filtered or unexported fields
}

func New

func New(options ...Option) *GoSvelt

func (*GoSvelt) Connect

func (gs *GoSvelt) Connect(path string, h HandlerFunc)

func (*GoSvelt) Delete

func (gs *GoSvelt) Delete(path string, h HandlerFunc)

func (*GoSvelt) Get

func (gs *GoSvelt) Get(path string, h HandlerFunc)

func (*GoSvelt) Middleware

func (gs *GoSvelt) Middleware(path string, fn MiddlewareFunc)

func (*GoSvelt) Options

func (gs *GoSvelt) Options(path string, h HandlerFunc)

func (*GoSvelt) Post

func (gs *GoSvelt) Post(path string, h HandlerFunc)

func (*GoSvelt) Put

func (gs *GoSvelt) Put(path string, h HandlerFunc)

func (*GoSvelt) Sse added in v1.3.0

func (gs *GoSvelt) Sse(path string, datach chan interface{}, closech chan struct{}, fn func())

func (*GoSvelt) Start

func (gs *GoSvelt) Start(addr string)

func (*GoSvelt) StartTLS

func (gs *GoSvelt) StartTLS(addr, cert, key string)

func (*GoSvelt) Static

func (gs *GoSvelt) Static(path, file string)

func (*GoSvelt) Svelte

func (gs *GoSvelt) Svelte(
	path, svelteFile string,
	handlerFn SvelteHandlerFunc,
	options ...SvelteOption,
)

help to server Svelte files to client

func (*GoSvelt) SvelteMiddleware

func (gs *GoSvelt) SvelteMiddleware(path string, fn SvelteMiddlewareFunc)

type HandlerFunc

type HandlerFunc func(c *Context) error

func Json added in v1.4.0

func Json(j interface{}) HandlerFunc

func Status added in v1.4.0

func Status(code int) HandlerFunc

func String added in v1.4.0

func String(str string) HandlerFunc

type Map

type Map map[string]interface{}

func (Map) Add

func (m Map) Add(key string, value interface{})

func (Map) Del

func (m Map) Del(key string)

func (Map) Get

func (m Map) Get(key string) interface{}

type MiddlewareFunc

type MiddlewareFunc func(next HandlerFunc) HandlerFunc

type Option added in v1.4.0

type Option func(*Options)

type Options added in v1.4.0

type Options struct {
	// contains filtered or unexported fields
}

type SseEvent added in v1.3.0

type SseEvent struct {
	Name string // event name
	Data string // event datas
}

sse event

type SvelteHandlerFunc

type SvelteHandlerFunc func(c *Context, svelte Map) error

type SvelteMiddlewareFunc

type SvelteMiddlewareFunc func(next SvelteHandlerFunc) SvelteHandlerFunc

type SvelteOption added in v1.4.0

type SvelteOption func(*SvelteOptions)

type SvelteOptions added in v1.4.0

type SvelteOptions struct {
	// contains filtered or unexported fields
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL