staticbackend

package module
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2022 License: MIT Imports: 47 Imported by: 1

README

StaticBackend logo

p.s. If you'd like to contribute to an active Go project, you've found a nice one in my biased opinion.

StaticBackend - simple backend for your apps

StaticBackend is a simple backend API that handles user management, database, file storage, forms, real-time experiences via channel/topic-based communication, and server-side functions for web and mobile applications.

You can think of it as a lightweight Firebase replacement you may self-host. Less vendor lock-in, and your data stays in your control.

Table of content

Import as Go package

As of v1.4.1 StaticBackend offers an importable Go package removing the need to self-host the backend API while keeping all functionalities from your Go program.

Example usage
package main

import (
	"fmt"
	"log"
	"time"

	"github.com/staticbackendhq/core/backend"
	"github.com/staticbackendhq/core/config"
	"github.com/staticbackendhq/core/model"
)

type Task struct {
	ID        string `json:"id"`
	AccountID string `json:"accountId"`
	Title     string `json:"title"`
	Done      bool   `json:"done"`
}

func main() {
	cfg := config.AppConfig{
		AppEnv: "dev",
		Port:   "8099",
		DatabaseURL:     "mem",
		DataStore:       "mem",
		LocalStorageURL: "http://localhost:8099",
	}
	// this initialized the backend from config
	backend.Setup(cfg)

	// You can access most of the raw building blocks directly from the 
	// package exported variables (which are interface) initialized via the 
	// config you pass

	// Set a value in the cache
	backend.Cache.Set("key", "value")

	// For strongly-typed database functionalities

	// in a real app you'd have a middleware handling identifying and fetching a 
	// model.DatabaseConfig for the current request. For this README sample 
	// we're faking a real call which would fail if ran.
	base, _ := backend.DB.FindDatabase("current-web-request-db-id")

	// let's create a user in this new Database
	usr := backend.Membership(base)
	sessionToken, user, err := usr.CreateAccountAndUser("[email protected]", "passwd123456", 100)
	if err != nil {
		log.Fatal(err)
	}

	// we simulate having authenticating this user (from middleware normally)
	// in a real app you'd store the sessionToken in your user's 
	// app (cookie, local storage, etc)
	// You'd need to have a middleware responsible of validating this token 
	// and have a model.Auth for the rest of your pipeline.
	auth := model.Auth{
		AccountID: user.AccountID,
		UserID:    user.ID,
		Email:     user.Email,
		Role:      user.Role,
		Token:     user.Token,
	}

	// we create a strongly-typed instance of the "tasks" collection
	// so we have full CRUD / Queries functions for your Task type
	tasks := backend.Collection[Task](auth, base, "tasks")

	newTask := Task{Title: "my task", Done: false}

	newTask, err = tasks.Create(newTask)
	if err != nil {
		log.Fatal(err)
	}
}
Documentation for the backend Go package

Refer to the Go documentation to know about all functions and examples.

What can you build

I built StaticBackend with the mindset of someone tired of writing the same code over and over on the backend. If your application needs one or all of user management, database, file storage, real-time interactions, it should be a good fit.

I'm personally using it to build SaaS:

En Pyjama - an online course platform for kids

Abandoned projects:

It can be used from client-side and/or server-side.

How it works / dev workflow

The main idea is that StaticBackend is your backend API for your applications. A performant free and open-source self-hosted Firebase alternative.

Note that it can also be used from your backend code as well.

Once you have an instance running and your first app created, you may install the JavaScript client-side library:

$> npm install @staticbackend/js

Let's create a user account and get a session token and create a task document in the tasks collection:

import { Backend } from "@staticbackend/js";

const bkn = new Backend("your_public-key", "dev");

let token = "";

login = async () => {
	const res = await bkn.register("[email protected]", "password");
	if (!res.ok) {
		console.error(res.content);
		return;
	}
	token = res.content;

	createTask();
}

createTask = async () => {
	const task = {
		desc: "Do something for XYZ",
		done: false
	};

	const res = bkn.create(token, "tasks", task);
	if (!res.ok) {
		console.error(res.content);
		return;
	}
	console.log(res.content);
}

The last console.log prints

{
	"id": "123456-unique-id",
	"accountId": "aaa-bbb-unique-account-id",
	"desc": "Do something for XYZ",
	"done": false
}

From there you build your application using the database CRUD and query functions, the real-time component, the storage API, etc.

StaticBackend provides commonly used building blocks for web applications.

You may use server-side libraries for Node, Python and Go or use an HTTP client and use your preferred language.

Get started with the self-hosted version

Deploy buttons

Heroku: Deploy an instance to your Heroku account.

Deploy

Render: Deploy an instance to your Render account

Deploy to Render

Docker or manual setup

Get started with self-hosted version

Click on the image above to see a video showing how to get started with the self-hosted version.

Please refer to this guide here.

We also have this blog post that includes the above video.

If you have Docker & Docker Compose ready, here's how you can have your server up and running in dev mode in 30 seconds:

$> git clone [email protected]:staticbackendhq/core.git
$> cd core
$> cp .demo.env .env
$> docker build . -t staticbackend:latest
$> docker-compose -f docker-compose-demo.yml up

Test your instance:

$> curl -v http://localhost:8099/db/test

You should get an error as follow:

< HTTP/1.1 401 Unauthorized
< Content-Type: text/plain; charset=utf-8
< Vary: Origin
< Vary: Access-Control-Request-Method
< Vary: Access-Control-Request-Headers
< X-Content-Type-Options: nosniff
< Date: Tue, 03 Aug 2021 11:40:15 GMT
< Content-Length: 33
< 
invalid StaticBackend public key

This is normal, as you're trying to request protected API, but you're all set.

The next step is to visit http://localhost:8099 and create your first app. Please note that in dev mode you'll have to look at your docker compose output terminal to see the content of the email after creating your app. This email contains all the keys and your super user account information.

Documentation

We're trying to have the best experience possible reading our documentation.

Please help us improve if you have any feedback.

Documentation with example using our libraries or curl:

Librairies & CLI

We provide a CLI for local development if you want to get things started without any infrastructure and for prototyping / testing.

You can use the CLI to manage your database, form submissions, and deploy server-side-functions. We have an alpha Web UI as well to manage your resources.

We have a page listing our client-side and server-side libraries.

Examples

If you'd like to see specific examples please let us know via the Discussions tab.

Here's the examples we have created so far:

Deploying in production

We've not written anything yet regarding deploying, but once you have the core` built into a binary and have access to either PostgreSQL or MongoDB, and Redis in production you should be able to deploy it like any other Go server.

We'll have documentation and an example soon for deploying to DigitalOcean.

Feedback & contributing

If you have any feedback (good or bad) we'd be more than happy to talk. Please use the Discussions tab.

Same for contributing. The easiest is to get in touch first. We're working to make it easier to contribute code. If you'd like to work on something precise let us know.

Here are videos made specifically for people wanting to contribute:

Check the contributing file for details.

Help

If you're looking to help the project, here are some ways:

  • Use it and share your experiences.
  • Sponsor the development via GitHub sponsors.
  • Spread the words, a tweet, a blog post, any mention is helpful.
  • Join the Discord server.

Documentation

Index

Constants

View Source
const (
	OAuthProviderTwitter  = "twitter"
	OAuthProviderFacebook = "facebook"
	OAuthProviderGoogle   = "google"
)
View Source
const (
	AppEnvDev  = "dev"
	AppEnvProd = "prod"
)

Variables

This section is empty.

Functions

func ShiftPath

func ShiftPath(p string) (head, tail string)

func Start

func Start(c config.AppConfig, log *logger.Logger)

Start starts the web server and all dependencies services

Types

type ConvertParam added in v1.3.0

type ConvertParam struct {
	ToPDF    bool   `json:"toPDF"`
	URL      string `json:"url"`
	FullPage bool   `json:"fullpage"`
}

type Database

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

type ExternalLogins added in v1.4.0

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

type ExternalUser added in v1.4.0

type ExternalUser struct {
	Token     string `json:"token"`
	Email     string `json:"email"`
	Name      string `json:"name"`
	FirstName string `json:"first"`
	LastName  string `json:"last"`
	AvatarURL string `json:"avatarUrl"`
}

type Flash

type Flash struct {
	Type    string
	Message string
}

type Hub

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

Hub maintains the set of active clients and broadcasts messages to the clients.

type Socket

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

Socket is a middleman between the websocket connection and the hub.

type ViewData

type ViewData struct {
	Title      string
	Language   string
	ActiveMenu string
	Flash      *Flash
	Data       interface{}
}

Directories

Path Synopsis
Package backend allows a Go program to import a standard Go package instead of self-hosting the backend API.
Package backend allows a Go program to import a standard Go package instead of self-hosting the backend API.
Package cache handles caching and pub/sub.
Package cache handles caching and pub/sub.
Package middleware exposes middlewares and helpers functions related to context get/set of DatabaseConfig and Auth.
Package middleware exposes middlewares and helpers functions related to context get/set of DatabaseConfig and Auth.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳