rest

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2020 License: MIT Imports: 8 Imported by: 0

README

Rest GO - Helpful library for Rest API

Build Status eder Go Report Card codecov

A package that provide many helpful methods for working with rest api.

And if u are tired of written, this:


func SomeHandler(w http.ResponseWriter, r *http.Request) {

    w.Header().Add("Content-Type", "application/json")

    product := &product{"Smart TV", 50.00}
    
    bytes, err := json.Marshal(product)
    
    if err != nil {
    	w.WriteHeader(http.StatusInternalServerError)
        // this is super bad!
        message := fmt.Sprintf("{\"message\": \"%s\"}", err.Error())
    	w.Write([]byte(message))
        return
    }
    
    w.WriteHeader(http.StatusOk)
    w.Write(bytes)
}

Get started:

rest package

The rest package provides some helpful methods that allow you to write better rest api in GO.

  • Allows for very readable code

See it in action:

package yours

import (
    "github.com/edermanoel94/rest-go"
    "net/http"
)

type product struct {
    Name  string `json:"name"`
    Price float32 `json:"price"`
}

func SomeHandler(w http.ResponseWriter, r *http.Request) {
    rest.Marshalled(w, &product{"Smart TV", 50.00}, http.StatusOK)
}

A payload send to your API and desarialize to a struct, to easy!

package yours

import (
    "github.com/edermanoel94/rest-go"
    "net/http"
)

type product struct {
    Name  string `json:"name"`
    Price float32 `json:"price"`
}

// [POST] body: {"name": "eder", "price": 20.00}
func SomePostHandler(w http.ResponseWriter, r *http.Request) {

    product := product{}
    err := rest.GetBody(r.Body, &product)
    if err != nil {
        // do stuff with error
    }
    // Do stuff...
}    

Working with mux package to check if path variable exist.

package yours

import (
    "github.com/edermanoel94/rest-go"
    "github.com/gorilla/mux"
    "net/http"
)

type product struct {
    Name  string `json:"name"`
    Price float32 `json:"price"`
}

// [GET] url: /product/{id}
func SomePostHandler(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    err := rest.CheckPathVariables(params, "id")
    if err != nil {
        // do stuff with error
    }
}

TODO List

  • Working with custom errors
  • Add Response for ALB and API Gateway
  • Benchmarking (Memory, CPU)
  • Working with CheckPathVariables and GetPathVariable in Standard library
  • More tests
  • Working with pagination

Installation

To install, use go get:

go get github.com/edermanoel94/rest-go

Example

To install and build:

cd examples

And use gomod for install packages:

go mod tidy && go mod vendor

Then, to run:

go build

Contributing

Please feel free to submit issues, fork the repository and send pull requests!


License

This project is licensed under the terms of the MIT license.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrNotValidJson = errors.New("not a valid json")
)

Functions

func CheckPathVariables

func CheckPathVariables(params map[string]string, pathVariables ...string) error

CheckPathVariables see if any pathVariables match on params, if dont, add to a slice. Actually this works just on mux.Vars() TODO: make working in standard library

Example
params := make(map[string]string)

params["id"] = "21321423"

err := rest.CheckPathVariables(params, "id")

if err != nil {
	// do stuff with error
}
Output:

func Error

func Error(w http.ResponseWriter, err error, code int) (int, error)

Error send a error to respond json, can send a non-struct which implements error.

Example
err := errors.New("cannot create product")

recorder := httptest.NewRecorder()

rest.Error(recorder, err, http.StatusOK)

result := recorder.Result()

defer result.Body.Close()

_, _ = io.Copy(os.Stdout, result.Body)
Output:

{"message":"cannot create product"}

func GetBody

func GetBody(reader io.ReadCloser, result interface{}) error

GetBody get the content of body on request and unmarshal a pointer to a <T> to attach on body

Example
product := struct {
	Name string `json:"name"`
}{}

readerCloser := ioutil.NopCloser(strings.NewReader("{\"name\": \"eder\"}"))

err := rest.GetBody(readerCloser, &product)

if err != nil {
	// do stuff with error
}
Output:

func GetPathVariable

func GetPathVariable(key string, params map[string]string) string

GetPathVariable

func Marshalled

func Marshalled(w http.ResponseWriter, v interface{}, code int) (int, error)

Marshalled use pointer to marshall and respond json

Example
product := struct {
	Name  string  `json:"name"`
	Price float32 `json:"price"`
}{
	Name:  "Smart TV",
	Price: 150.20,
}

recorder := httptest.NewRecorder()

rest.Marshalled(recorder, &product, http.StatusOK)

result := recorder.Result()

defer result.Body.Close()

_, _ = io.Copy(os.Stdout, result.Body)
Output:

{"name":"Smart TV","price":150.2}

func Response

func Response(w http.ResponseWriter, body []byte, code int) (int, error)

Response send slice of bytes to respond json

Types

This section is empty.

Jump to

Keyboard shortcuts

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