Giter Club home page Giter Club logo

go-base's Introduction

Go Restful API Boilerplate

GoDoc Badge GoReportCard Badge

Easily extendible RESTful API boilerplate aiming to follow idiomatic go and best practice.

The goal of this boiler is to have a solid and structured foundation to build upon on.

Any feedback and pull requests are welcome and highly appreciated. Feel free to open issues just for comments and discussions.

Features

The following feature set is a minimal selection of typical Web API requirements:

Start Application

  • Clone and change into this repository

Local

  • Create a postgres database and set environment variables for your database accordingly if not using below defaults
  • Run the application to see available commands: go run main.go
  • Run all migrations from database/migrate folder: go run main.go migrate
  • Run the application with command serve: go run main.go serve

Using Docker Compose

  • First start the database only: docker compose up -d postgres
  • Once initialize the database by running all migrations in database/migrate folder: docker compose exec server ./main migrate
  • Start the api server: docker compose up server

API Routes

Authentication

For passwordless login following routes are available:

Path Method Required JSON Header Description
/auth/login POST email the email you want to login with (see below)
/auth/token POST token the token you received via email (or printed to stdout if smtp not set)
/auth/refresh POST Authorization: "Bearer refresh_token" refresh JWTs
/auth/logout POST Authorizaiton: "Bearer refresh_token" logout from this device

Example API

Besides /auth/_ the API provides two main routes /api/_ and /admin/*, as an example to separate application and administration context. The latter requires to be logged in as administrator by providing the respective JWT in Authorization Header.

Check routes.md for a generated overview of the provided API routes.

Client API Access and CORS

The server is configured to serve a Progressive Web App (PWA) client from ./public folder (this repo only serves an example index.html, see below for a demo PWA client to put here). In this case enabling CORS is not required, because the client is served from the same host as the api.

If you want to access the api from a client that is serverd from a different host, including e.g. a development live reloading server with below demo client, you must enable CORS on the server first by setting environment variable ENABLE_CORS=true on the server to allow api connections from clients serverd by other hosts.

Demo client application

For demonstration of the login and account management features this API serves a demo Vue.js PWA. The client's source code can be found here. Build and put it into the api's ./public folder, or use the live development server (requires CORS enabled).

Outgoing emails containing the login token will be print to stdout if no valid email smtp settings are provided by environment variables (see table below). If EMAIL_SMTP_HOST is set but the host can not be reached the application will exit immediately at start.

Use one of the following bootstrapped users for login:

A deployed version can also be found on Heroku

Testing

Package auth/pwdless contains example api tests using a mocked database. Run them with: go test -v ./...

Environment Variables

By default viper will look at $HOME/.go-base.yaml for a config file. Setting your config as Environment Variables is recommended as by 12-Factor App.

Name Type Default Description
PORT string localhost:3000 http address (accepts also port number only for heroku compability)
LOG_LEVEL string debug log level
LOG_TEXTLOGGING bool false defaults to json logging
DB_NETWORK string tcp database 'tcp' or 'unix' connection
DB_ADDR string localhost:5432 database tcp address or unix socket
DB_USER string postgres database user name
DB_PASSWORD string postgres database user password
DB_DATABASE string postgres database shema name
AUTH_LOGIN_URL string http://localhost:3000/login client login url as sent in login token email
AUTH_LOGIN_TOKEN_LENGTH int 8 length of login token
AUTH_LOGIN_TOKEN_EXPIRY time.Duration 11m login token expiry
AUTH_JWT_SECRET string random jwt sign and verify key - value "random" creates random 32 char secret at startup (and automatically invalidates existing tokens on app restarts, so during dev you might want to set a fixed value here)
AUTH_JWT_EXPIRY time.Duration 15m jwt access token expiry
AUTH_JWT_REFRESH_EXPIRY time.Duration 1h jwt refresh token expiry
EMAIL_SMTP_HOST string email smtp host (if set and connection can't be established then app exits)
EMAIL_SMTP_PORT int email smtp port
EMAIL_SMTP_USER string email smtp username
EMAIL_SMTP_PASSWORD string email smtp password
EMAIL_FROM_ADDRESS string from address used in sending emails
EMAIL_FROM_NAME string from name used in sending emails
ENABLE_CORS bool false enable CORS requests

go-base's People

Contributors

dhax avatar piotrkochan avatar whilei avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-base's Issues

provide .go-base.yaml.example pls

hello dhax and team, nice project. but i confuse for adding .go-base.yaml without example. its really nice to have if u prodive it. thanks

Swagger

You should consider adding support for Swagger/OpenAPI.

Other database providers

Id love to use this with mongodb it would be great if there was an example or some db abstraction to make it easy to plug in another type

how to start

dev@dev-x:$ cd Documentos
dev@dev-x:
/Documentos$ cd go-base
dev@dev-x:/Documentos/go-base$ go build OK
dev@dev-x:
/Documentos/go-base$ go run main.go
A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.

Usage:
go-base [command]

Available Commands:
gendoc Generate project documentation
help Help about any command
migrate use go-pg migration tool
serve start http server with configured api

Flags:
--config string config file (default is $HOME/.go-base.yaml)
--db_debug log sql to console
-h, --help help for go-base

Use "go-base [command] --help" for more information about a command.
dev@dev-x:/Documentos/go-base$ go-base migrate init
go-base: comando não encontrado
dev@dev-x:
/Documentos/go-base$ go-base migrate
go-base: comando não encontrado
dev@dev-x:/Documentos/go-base$ go-base serve
go-base: comando não encontrado
dev@dev-x:
/Documentos/go-base$

Some dependency confilict, not able to boot up following instructions

  • Cloned repo
  • DATABASE_URL exported
  • Installed dependencies
$ dep init
  • Failing in build
# github.com/dhax/go-base/auth/jwt
auth/jwt/claims.go:17: undefined: jwtauth.Claims
auth/jwt/claims.go:52: undefined: jwtauth.Claims
auth/jwt/token.go:40: undefined: jwtauth.Claims
auth/jwt/token.go:41: undefined: jwtauth.Claims
auth/jwt/tokenauth.go:41: undefined: jwtauth.Claims
auth/jwt/tokenauth.go:54: undefined: jwtauth.Claims
auth/jwt/tokenauth.go:62: undefined: jwtauth.Claims
# github.com/dhax/go-base/vendor/github.com/go-pg/migrations
vendor/github.com/go-pg/migrations/db.go:17: syntax error: unexpected = in type declaration```

Dockerfile

Docker can be great to this project, you should consider to add it.

Actually i'am working in a dockerfile to a personal project using your boilerplate.

Add API with insert

Hi, could you pls review my changes

When inserting without specifying id (auto increment, primary key) it returns

{
    "status": "Unprocessable Entity",
    "error": "ERROR #23505 duplicate key value violates unique constraint \"reports_pkey\""
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.