项目作者: gbrlsnchs

项目描述 :
RESTful HTTP handler for Go
高级语言: Go
项目地址: git://github.com/gbrlsnchs/rest.git
创建时间: 2018-10-18T19:15:54Z
项目社区:https://github.com/gbrlsnchs/rest

开源协议:MIT License

下载


rest (RESTful HTTP handler for Go)

Build Status
Sourcegraph
GoDoc
Minimal Version

About

This package implements a simple RESTful HTTP handler that facilitates receiving requests or sending responses in JSON or XML by using a custom context.

Usage

Full documentation here.

Installing

Go 1.10

vgo get -u github.com/gbrlsnchs/rest

Go 1.11 or after

go get -u github.com/gbrlsnchs/rest

Importing

  1. import (
  2. // ...
  3. "github.com/gbrlsnchs/rest"
  4. )

Setting a wrapper

Consider the following type to be received / sent

  1. type message struct {
  2. content string `json:"content,omitempty"`
  3. }

Now, set the main handler

  1. http.Handle("/", &rest.Wrapper{
  2. Handler: rest.HandlerFunc(func(ctx *rest.Context) {
  3. var ping message
  4. if err := ctx.ReceiveJSON(&ping); err != nil {
  5. // handle error
  6. }
  7. if ping.content != "ping" {
  8. ctx.Send(http.StatusBadRequest)
  9. return
  10. }
  11. pong := message{"pong"}
  12. ctx.SendJSON(pong, http.StatusOK)
  13. }),
  14. RecoverHandler: rest.HandlerFunc(func(ctx *rest.Context) {
  15. ctx.Send(http.StatusInternalServerError)
  16. }),
  17. })

Contributing

How to help