Utilities for a JSON-based API.

Matt Baer 38cdc56928 Add ReqJSON func for determining JSON requests 1 year ago
.gitignore 4ec36a262e Add text editor temp files to gitignore 2 years ago
LICENSE 3c220a424b Initial commit 2 years ago
README.md 2e2812d5f1 Add IRC badge to README 1 year ago
doc.go fa4b445d40 Rename impart.go to doc.go 1 year ago
errors.go 9c5649c3ba Add func and package comments 1 year ago
request.go 38cdc56928 Add ReqJSON func for determining JSON requests 1 year ago
response.go b97c7b280f Add WriteRedirect helper func 1 year ago

README.md

impart

MIT license Public Slack discussion

impart is a library for the final layer between the API and the consumer. It's used in the latest Write.as and HTMLhouse APIs.

We're still in the early stages of development, so there may be breaking changes.

Example use

package main

import (
	"fmt"
	"github.com/writeas/impart"
	"net/http"
)

type handlerFunc func(w http.ResponseWriter, r *http.Request) error

func main() {
	http.HandleFunc("/", handle(index))
	http.ListenAndServe("127.0.0.1:8080", nil)
}

func index(w http.ResponseWriter, r *http.Request) error {
	fmt.Fprintf(w, "Hello world!")

	return nil
}

func handle(f handlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		handleError(w, r, func() error {
			// Do authentication...

			// Handle the request
			err := f(w, r)

			// Log the request and result...

			return err
		}())
	}
}

func handleError(w http.ResponseWriter, r *http.Request, err error) {
	if err == nil {
		return
	}

	if err, ok := err.(impart.HTTPError); ok {
		impart.WriteError(w, err)
		return
	}

	impart.WriteError(w, impart.HTTPError{http.StatusInternalServerError, "Internal server error :("})
}