Documentation
¶
Index ¶
- Variables
- func CheckPathVariables(params map[string]string, pathVariables ...string) error
- func Error(w http.ResponseWriter, err error, code int) (int, error)
- func GetBody(reader io.ReadCloser, result interface{}) error
- func GetPathVariable(key string, params map[string]string) string
- func Marshalled(w http.ResponseWriter, v interface{}, code int) (int, error)
- func Response(w http.ResponseWriter, body []byte, code int) (int, error)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var (
ErrNotValidJson = errors.New("not a valid json")
)
Functions ¶
func CheckPathVariables ¶
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 ¶
package main
import (
"github.com/edermanoel94/rest-go"
)
func main() {
params := make(map[string]string)
params["id"] = "21321423"
err := rest.CheckPathVariables(params, "id")
if err != nil {
// do stuff with error
}
}
Output:
func Error ¶
Error send a error to respond json, can send a non-struct which implements error.
Example ¶
package main
import (
"errors"
"github.com/edermanoel94/rest-go"
"io"
"net/http"
"net/http/httptest"
"os"
)
func main() {
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 ¶
package main
import (
"github.com/edermanoel94/rest-go"
"io/ioutil"
"strings"
)
func main() {
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 ¶
GetPathVariable
func Marshalled ¶
func Marshalled(w http.ResponseWriter, v interface{}, code int) (int, error)
Marshalled use pointer to marshall and respond json
Example ¶
package main
import (
"github.com/edermanoel94/rest-go"
"io"
"net/http"
"net/http/httptest"
"os"
)
func main() {
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}
Types ¶
This section is empty.
Click to show internal directories.
Click to hide internal directories.