jasco

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2017 License: MIT Imports: 13 Imported by: 21

README

jasco: Compact JSON API Server library version 1

jasco is a compact library to build a JSON API server. It's written in Go and built on github.com/gocraft/web.

Requirements

jasco requires Go 1.4.2 or later.

Installation

$ go get gopkg.in/pfnet/jasco.v1

Example

example.go:

package main

import (
    "net/http"

    "github.com/gocraft/web"
    "gopkg.in/pfnet/jasco.v1"
)

type Context struct {
    *jasco.Context
}

func (c *Context) Get(rw web.ResponseWriter, req *web.Request) {
    c.Render(map[string]interface{}{
        "hello": "world",
        "num":   10,
        "obj": map[string]interface{}{
            "a": 1,
            "b": "2",
            "c": []interface{}{3.4, "5"},
        },
    })
}

func (c *Context) Echo(rw web.ResponseWriter, req *web.Request) {
    var js map[string]interface{}
    if err := c.ParseBody(&js); err != nil {
        c.ErrLog(err.Err).Error("Cannot parse the request body")
        c.RenderError(err)
        return
    }
    c.Render(js)
}

func main() {
    root := jasco.New("", nil)
    router := root.Subrouter(Context{}, "/")
    router.Get("/", (*Context).Get)
    router.Post("/", (*Context).Echo)
    http.ListenAndServe(":10080", root)
}

Run the example:

$ go run sample.go

Test:

$ curl http://localhost:10080/
{"hello":"world","num":10,"obj":{"a":1,"b":"2","c":[3.4,"5"]}}
$ curl -XPOST -d'{"test":"data"}' http://localhost:10080/
{"test":"data"}

Logging

jasco uses github.com/sirupsen/logrus as a logger. Pass a logger that the application uses to jasco.New. By default, the default logger of logrus will be used.

Context.AddLogField("field", value) adds a field to be logged by logrus. Because gocraft/web creates a context for each request, a field added to the context is only available while the request is being processed.

Documentation

Index

Constants

View Source
const (
	// SomethingWentWrong is an error message that doesn't explain anything
	// to users except something went wrong.
	SomethingWentWrong = "Something went wrong. Please try again later."
)

Variables

This section is empty.

Functions

func New

func New(prefix string, logger *logrus.Logger) *web.Router

New creates a new web.Router based on Context.

Types

type Context

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

Context is a context object for gocraft/web.

func (*Context) AddLogField

func (c *Context) AddLogField(key string, value interface{})

AddLogField adds a field shown in all log entries written via this context.

func (*Context) Body

func (c *Context) Body() ([]byte, *Error)

Body returns a slice containing whole request body. It caches the result so that controllers can call this method as many time as they want.

When the request body is empty (i.e. Read(req.Body) returns io.EOF), this method returns and caches an empty body slice (could be nil) and a nil error.

Noet that this method returns an error as *Error, not error. So, the return value shouldn't be assigned to error type to avoid confusing nil comparison problem.

func (*Context) CLog

func (c *Context) CLog(callerDepth int) *logrus.Entry

CLog returns the logger having meta information and the information of the caller with the given callDepth. This method is useful when a utility function wants to write a log but it want to have "file" and "line" of the caller. When callerDepth is 0, "file" and "line" of the caller of this method are used.

func (*Context) ErrLog

func (c *Context) ErrLog(err error) *logrus.Entry

ErrLog returns the logger with error information.

func (*Context) Log

func (c *Context) Log() *logrus.Entry

Log returns the logger having meta information.

func (*Context) NotFoundHandler

func (c *Context) NotFoundHandler(rw web.ResponseWriter, req *web.Request)

NotFoundHandler handles 404.

func (*Context) ParseBody

func (c *Context) ParseBody(v interface{}) *Error

ParseBody parses the request body as a JSON. The argument v is directly passed to json.Unmarshal.

func (*Context) PathParams

func (c *Context) PathParams() *PathParams

PathParams returns parameters embedded in the URL.

func (*Context) RemoveLogField

func (c *Context) RemoveLogField(key string)

RemoveLogField removes a field to be logged.

func (*Context) Render

func (c *Context) Render(v interface{})

Render renders a successful result as a JSON.

func (*Context) RenderError

func (c *Context) RenderError(e *Error)

RenderError renders a failing result as a JSON.

func (*Context) RenderRaw

func (c *Context) RenderRaw(status int, v interface{})

RenderRaw renders a JSON with the given status code.

func (*Context) RequestID

func (c *Context) RequestID() uint64

RequestID returns the ID that is unique to the request.

func (*Context) SetHTTPStatus

func (c *Context) SetHTTPStatus(s int)

SetHTTPStatus sets HTTP status of the response. This method is used when an action doesn't render JSON.

func (*Context) SetLogger

func (c *Context) SetLogger(l *logrus.Logger)

SetLogger sets the logger to the context. The logger must be set before any action is invoked.

type Error

type Error struct {
	// Code has an error code of this error. It always have
	// a single alphabet prefix and 4-digit error number.
	Code string `json:"code"`

	// Message contains a user-friendly error message for users
	// of WebUI or clients of API. It MUST NOT have internal
	// error information nor debug information which are
	// completely useless for them.
	Message string `json:"message"`

	// RequestID has an ID of the request which caused this error.
	// This value is convenient for users or clients to report their
	// problems to the development team. The team can look up incidents
	// easily by greping logs with the ID.
	//
	// The type of RequestID is string because it can be
	// very large and JavaScript might not be able to handle
	// it as an integer.
	RequestID string `json:"request_id"`

	// Status has an appropriate HTTP status code for this error.
	Status int `json:"-"`

	// Err is an internal error information which should not be shown to users
	// directly.
	Err error `json:"-"`

	// Meta contains arbitrary information of the error.
	// What the information means depends on each error.
	// For instance, a validation error might contain
	// error information of each field.
	Meta map[string]interface{} `json:"meta"`
}

Error has the error information reported to clients of API.

func NewError

func NewError(code string, msg string, status int, err error) *Error

NewError creates a new Error instance.

func NewInternalServerError

func NewInternalServerError(err error) *Error

NewInternalServerError creates an internal server error response having an error information.

func (*Error) SetRequestID

func (e *Error) SetRequestID(id uint64)

SetRequestID set the ID of the current request to Error.

type PathParams

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

PathParams contains parameters embedded in the URL supported by gocraft/web

func (*PathParams) Int

func (p *PathParams) Int(key string, defaultValue uint64) (uint64, error)

Int returns a positive integer value correspoding to the key as uint64. When the key doesn't exist, it returns defaultValue. It returns an error if it cannot parse the path string parameter as an integer or the value is greater than or equal to 2^63.

func (*PathParams) RequiredInt

func (p *PathParams) RequiredInt(key string) (uint64, error)

func (*PathParams) RequiredString

func (p *PathParams) RequiredString(key string) (string, error)

RequiredString return a string value corresponding to the key. When the key doesn't exist, it returns an error.

func (*PathParams) String

func (p *PathParams) String(key string, defaultValue string) string

String returns a string value corresponding to key. When the key doesn't exist, it returns defaultValue.

Jump to

Keyboard shortcuts

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