ejunjsh / gorest

a restful framework with go
20 stars 5 forks source link

gorest

Build Status

baby-gopher

a restful go framework

install

go get github.com/ejunjsh/gorest

usage

import

import "github.com/ejunjsh/gorest"

create a app and run a server

app:=gorest.NewApp()
app.[Get/Post/Delete/Put/Error]
app.Run(":8081")

supports 4 methods of http request

app.Get("/", func(r *gorest.HttpRequest, w gorest.HttpResponse) error {...})
app.Post("/", func(r *gorest.HttpRequest, w gorest.HttpResponse) error {...})
app.Delete("/", func(r *gorest.HttpRequest, w gorest.HttpResponse) error {...})
app.Put("/", func(r *gorest.HttpRequest, w gorest.HttpResponse) error {...})

supports parameters from url path

app.Get("/:abc/:cba", func(r *gorest.HttpRequest, w gorest.HttpResponse) error {
        fmt.Println(r.PathParams["abc"],r.PathParams["cba"])
        return nil
})

supports string,json,xml,file,template as result of return

app.Get("/", func(r *gorest.HttpRequest, w gorest.HttpResponse) error {
        return  w.WriteJson(jsonObj)
                //w.WriteString(str)
                //w.WriteXml(xmlObj)
                //w.WriteFile("/Users/zhouff/file.txt")
                //w.WriteTemplates(data,"/Users/zhouff/index.html","/Users/zhouff/header.html")
})

supports dealing with errors

app.Error(func(err error, r *gorest.HttpRequest, w gorest.HttpResponse){
        if e,ok:=err.(gorest.NoFoundError);ok {
            w.Write([]byte(e.Error()))
        }
        if e,ok:=err.(gorest.InternalError);ok {
            w.Write([]byte(e.Error()))
        }
})

see example