Giter VIP home page Giter VIP logo

jas's Introduction

JAS

JAS (JSON API Server) is a simple and powerful REST API framework for Go. 中文版 README

Build Status Build Status

Requirement

Require Go 1.1+.

Features

  • No need to manually define any url routing rules, the rules are defined by your resource struct names and method names. No more inconsistencies between your url path and your method name.

  • Generate all the handled url paths seperated by "\n", so it can be used for reference or detect api changes.

  • Unobtrusive, JAS router is just a http.Handler, you can make it work with other http.Handlers as well as have multiple JAS routers on the same server.

  • Support HTTP Streaming, you can keep an connection open and send real-time data to the client, and get notified when the connection is closed on the client side.

  • Support extract parameters from json request body in any level of depth, so it can be used like JSON RPC.

  • Get and validate request parameter at the same time, support validate a integer, a string's min and max length or rune length, and match a regular expression.

  • Generate default response with the parameter name when validation failed, optionally log the error in Common Log Format.

  • Wrap all unhandled error into InternalError type, write response to the client with default message, and log the stacktraces and request infomation in Common Log Format. and provide a optional function parameter to do the extra error handlling work.

  • Provide an interface to handle errors, so you can define your own error type if the two default implementation can not meet your requirement.

  • Support gzip.

  • Highly configuarable.

Performance

JAS is a thin layer on top of net/http package, it adds about 1000ns operation time on every request, which means 99% of the performance when the qps number is around 10000.

But JAS will be faster than any regular expression routing solution. a single regular experssion match operation usually takes about 1000ns.

JAS router do not use regular expression, the routing performance would be constant as you define more resource and methods.

Install

go get github.com/coocood/jas

Only depends on a small assert package github.com/coocood/assrt for testing.

Get Started

Define a struct type and its methods, methods should have one argument of type *jas.Context, no return value.

type Hello struct {}

func (*Hello) Get (ctx *jas.Context) { // `GET /v1/hello`
	ctx.Data = "hello world"
	//response: `{"data":"hello world","error":null}`
}

func main () {
    router := jas.NewRouter(new(Hello))
    router.BasePath = "/v1/"
    fmt.Println(router.HandledPaths(true))
    //output: `GET /v1/hello`
    http.Handle(router.BasePath, router)
    http.ListenAndServe(":8080", nil)
}

Documentation

See Gowalker or godoc for complete documentation.

LICENSE

JAS is distributed under the terms of the MIT License. See LICENSE for details.

Contributiors

Jacob Olsen, doun, Olav

jas's People

Contributors

adsouza avatar coocood avatar doun avatar jakeo avatar oal avatar sriniprash 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

jas's Issues

ctx.Request.Body is nil when post json

package main

import(
"github.com/coocood/jas"
"net/http"
 "fmt"
"bytes"
)
type Add struct {}
 
func (*Add) Get (ctx *jas.Context) { 
	ctx.Data = "hello world"
 
}
func (*Add) Post (ctx *jas.Context) { 
 

    buf:=new(bytes.Buffer)
    buf.ReadFrom(ctx.Request.Body)

    fmt.Println(buf.String())


	ctx.Data = " world hello"
 
}
func main () {
router := jas.NewRouter(new(Add))
	http.Handle("/", router)
 http.ListenAndServe(":8080", nil)
}

curl -X POST http://localhost:8080/add -H "Content-Type: application/json" -d @data.json

Why jas donot have a default value in func RequireXXX

Some times default value is needed. But I have to use such code with jas.

str, err := ctx.FindString(paths...)
if err != nil {
    str = defaultStr
}

It is a little strange. Why cannot do it like that.

str := ctx.RequireDefaultString(defaultStr, paths...)

How to use ctx.Extra?

extra can store extra data generated/used by hook functions, e.g. 'BeforeServe'. ?
can I use like follow:

type request struct {
    reqStartTime time.Time
    requestId string
    reqData map[string]interface {}
}
func BeforeServeV1(ctx *jas.Context) {
    var req request
    req.reqStartTime = time.Now()
    req.requestId = GenUUID()
    d, err := ctx.FindString("d")
    req.reqData,err  = json.Unmarshal([]byte(d))

   ctx.Extra = req
}

reqData will be used in other router method. is it concurrent written safe?

Testing packages included on every build

Because assert.go is in the same directory as everything else, the build system pulls in all the testing libraries when you import JAS. You can verify this by running the compiled binary with --help. You'll see this:

-test.bench="": regular expression to select benchmarks to run
-test.benchmem=false: print memory allocations for benchmarks
-test.benchtime=1s: approximate run time for each benchmark
-test.blockprofile="": write a goroutine blocking profile to the named file after execution
-test.blockprofilerate=1: if >= 0, calls runtime.SetBlockProfileRate()
-test.cpu="": comma-separated list of number of CPUs to use for each test
-test.cpuprofile="": write a cpu profile to the named file during execution
-test.memprofile="": write a memory profile to the named file after execution
-test.memprofilerate=0: if >=0, sets runtime.MemProfileRate
-test.parallel=1: maximum test parallelism
-test.run="": regular expression to select tests and examples to run
-test.short=false: run smaller test suite to save time
-test.timeout=0: if positive, sets an aggregate time limit for all tests
-test.v=false: verbose: print additional output

One solution may be to move assert.go to an assert subdirectory and an assert package, then import it like so: "github.com/coocood/jas/assert".

{"data":null,"error":"Not Found"} when Post

package main

import(
"github.com/coocood/jas"
"net/http"
 "fmt"
)
type Hello struct {}
 
func (*Hello) Get (ctx *jas.Context) { 
	ctx.Data = "hello world"
 
}
func (*Hello) Post (ctx *jas.Context) { 
   fmt.Println(ctx.Request)
	ctx.Data = " world hello"
 
}


func main () {

    http.Handle("/add", jas.NewRouter(new(Hello)))
      http.ListenAndServe(":8080", nil)
    
    }

curl -X POST http://localhost:8080/add -H "Content-Type: application/json" -d @data.json

Add hooks

Do you think it would be doable/in the scope of this project, to add something akin to Rails before/after filters to hook into the request lifecycle ? It can be very useful for things like authentication/compression/caching ...

String IDs

I'm using a small embedded database called EJDB, and it stores object IDs similar to those used by MongoDB, RethinkDB etc: 51f959801a2a7c3300000000

These will not get parsed by jas, or at least I haven't found a way to make it work. I tried to use a Gap ":uid", but then I could only get the API to create addresses like "/api/users/:uid" and "/api/users/" wouldn't exist.

Do you know if there's a workaround to this, or is this something jas might support in the future?

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.