Socket
Socket
Sign inDemoInstall

github.com/mccolljr/attache

Package Overview
Dependencies
19
Alerts
File Explorer

Install Socket

Detect and block malicious and high-risk dependencies

Install

    github.com/mccolljr/attache

Package attache: an arsenal for the web. Attachè (mispronounced for fun as "Attachey", said like "Apache") is a new kind of web framework for go. It allows you to define your applications in terms of methods on a context type that is instantiated for each request. An Attachè Application is bootstrapped from a context type that implements the Context interface. In order to enforce that the context type is a struct type at compile time, embedding the BaseContext type is necessary to satisfy this interface. Functionality is provided by additional methods implemented on the context type. Attachè provides several capabilities (optional interfaces) that a Context type can implement. These interfaces take the form of "Has...". They are documented individually. Aside from these capabilites, a Context can provide several other types of methods: 1. Route methods Routing methods must follow the naming convention of <HTTP METHOD>_<[PathInCamelCase]> PathInCamelCase is optional, and defaults to the empty string. In this case, the method name would still need to include the underscore (i.e. GET_). The path which a routing method serves is determined by converting the PathInCamelCase to snake case, and then replacing underscores with the path separator. Examples: Route methods can take any number/types of arguments. Values are provided by the Application's dependency injection context for this request. If a value isn't available for an argument's type, the zero-value is used. Return values are unchecked, and really shouldn't be provided. That limitation is not enforced in the code, to provide flexibility. If a Context type provides a BEFORE_ method matching the name of the Route method, it will be run immediately before the Route method in the handler stack If a Context type provides an AFTER_ method matching the name of the Route method, it will be run immediately after the Route method in the handler stack. Although there is no hard enforcement, an AFTER_ method should assume the ResponseWriter has been closed. 2. Mount methods Mount methods must follow the naming convention of MOUNT_<[PathInCamelCase]> and have the signature func() (http.Handler, error). They are only called once, on an uninitialized Context during bootstrapping. If an error is returned (or the method panics), bootstrapping will fail. If there is no error, the returned http.Handler is mounted at the path specified by PathInCamelCase, using the same method as Routing methods. The mounted handler is called with the mounted prefix stripped from the request. 3. Guard methods Mount methods must follow the naming convention of GUARD_<[PathInCamelCase]>. The path at which a Guard method is applied is determined from PathInCamelCase, in the same way as a Route method. A Guard method will run for the path at which it is registered, as well as any paths that contain the guarded path. To prevent the handler stack from continuing execution, the Guard method must either panic or call one of the Attachè helper methods (Error, ErrorFatal, ErrorMessage, etc...). If there are multiple Guard methods on a path, they are run in they order they are encountered (i.e. the guards for shorter paths run before the guards for longer paths). 4. Provider methods Provider methods must follow the naming convention of PROVIDE_<UniqueDescriptiveName> and have the signature func(*http.Request) interface{}. Provider methods are called when a route or a guarded mount match the request's path. The returned value is available for injection into any handlers in the handler stack for the current request. Because of the frequency with which these are called, it is best to define as few as possible. Attachè also comes with a CLI. Currently, the supported commands are `attache new` and `attache gen`. Please see README.md for more info.


Version published

Readme

Source

Attache

godoc Go Report Card CircleCI

Since this project is still a work in progress, please make sure you test it out before deciding to use it.

Preface

A couple of years ago, I got an idea. At the time, it was a fuzzy concept for "some kind of web framework" for Go. I ignored this idea for the longest time, because I felt Go was not conducive to that kind of project. That's not a slight at Go, I just felt that the language didn't really need it. As time went on I started building code that I re-used between several personal (read: half-finished, never-published) projects. I started to coalesce those items into a package. Over time, that package became unruly. I started refactoring. I started standardizing. I started toying with weird ideas and making bad decisions, removing them, and trying something new.

Eventually, I ended up with Attache, a really lame play on words:

  1. Attachè, noun: person on the staff of an ambassador, typically with a specialized area of responsibility
  2. Attache, mispronounced like "Apache" ('cuz it's a web server)).

I've been using this "framework" (which I think of as more of a collection of tools) in some freelance work recently and I really enjoy it. It makes some things much easier by allowing me to avoid some boilerplate each time I start a web app that uses Go, but without forcing me into a particular application structure.

This is my longest running personal project. For better or for worse, I think it could use some new ideas and new eyes.

Documentation is a little sparse (I'm working on it, but it takes time and I have a full time job outside of this :( ).

I'm a little nervous. All of this is my own code right now. It feels weird to put so much out there for the community to see and judge. I like this, though, and I hope maybe you all will as well.

Installation

$> go get -u github.com/attache/attache/...

Usage

Getting Started

The CLI is the canonical way to start a new Attache application. An example of a working application can be found in examples/todo

Create a new Attache application
$> attache new -n MyApp
$> cd ./my_app

Inside the my_app folder, you will find the basic structure of the application:

/my_app/            - root
|  /models/         - directory where Attache generates models
|  /views/          - directory where Attache generates views
|  |  index.tpl
|  |  layout.tpl
|  /web/            - directory where frontend files live
|  |  /dist/        - default public file server root 
|  |  |  /css/
|  |  |  /img/
|  |  |  /js/
|  |  /src/         - where TypeScript, Less, Sass, etc. should be written before compiling
|  |  |  /script/
|  |  |  /styles/
|  /secret/         - files that should be ignored by git
|  |  run.sh
|  |  schema.sql
|  main.go          - basic application structure & startup
|  .at-conf.json    - Attache CLI configuration - don't touch this
|  .gitignore

Run

# from within the application's root directory
$> ./secret/run.sh

Then, visit http://localhost:8080/, you should see a page with

Welcome to your Attache application!

Database Connection

To get Attache to manage a database connection for you, embed the attache.DefaultDB type into your content type. You can do so by uncommenting the auto-generated line. This will inspect 2 environment variables, DB_DRIVER and DB_DSN, and attempt to use these to establisha a database connection. This connection will then be available to your Context's methods via the .DB() method of the embedded attache.DefaultDB type when a context is initialized by Attache to handle a request

type MyApp struct {
        // required
        attache.BaseContext

        // capabilities
        attache.DefaultFileServer
        attache.DefaultViews
        attache.DefaultDB // <--- UNCOMMENT THIS LINE
        // attache.DefaultSession // enable session storage
}

Once you have enabled database connectivity, you can begin to generate (or manually build)models to represent your schema.

Let's say you have todos table in your database.

CREATE TABLE `todos` (
	`title` TEXT PRIMARY KEY NOT NULL,
	`desc`  TEXT NOT NULL DEFAULT ""
);

You can use the CLI to generate a model, views, and routes.

Create a model, view, and routes
# from within the application's root directory
$> attache gen -n Todo -t todos -f Title:string:key -f Desc:string
# creates   ./models/todos.go
#           ./views/todos/create.tpl
#           ./views/todos/list.tpl
#           ./views/todos/update.tpl
#           ./todos_routes.go
Create just models, just views, or just routes
# from within the application's root directory

# just generate the model
$> attache gen -model [...]

# just generate the views
$> attache gen -views [...]

# just generate the routes
$> attache gen -routes [...]

# just generate some combination
$> attache gen -routes -models [...]
Replace existing files
# from within the application's root directory
$> attache gen -replace [...]
Generate JSON routes (and no views)

If you want to generate the routes to serve JSON data rather than views, you can include the -json flag in your command. This will generate routes for a JSON-based API, and prevent generation of views.

# from within the application's root directory
$> attache gen -json [...]
Use CLI plugin

The CLI is extensible. It can take advantage of dynamically linked plugins, which can be used like so:

# attempts to load plugin from $HOME/.attache/plugins/PLUGNAME.so
$> attache PLUGNAME [...]

Contributing

If you'd like to help, here are the high-level TODOs:
  1. Documentation Wiki
    • document the method naming conventions
    • document some example applications
    • etc...
  2. Add CLI plugins for common use cases
    • Generate content for features such as Authorization, REST API for a database schema, etc
    • Embed other code generation tools
      • github.com/xo/xo
      • github.com/cheekybits/genny
      • etc...
  3. Add CLI plugin subcommand for managing installation of plugins
    • maybe have a central repo with checksum verification?
  4. Add context capabilities for
    • Config (maybe github.com/spf13/viper)
  5. Code cleanup and package re-org

FAQs

Last updated on 30 Nov 2020

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc