jparser

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2022 License: MIT Imports: 7 Imported by: 0

README

Contributors Forks Stargazers Issues MIT License


Go HTTP JParser

A simple JSON parser and encoding for your Go REST servers.
Report Bug · Request Feature

http-jparser is a simple Go library used for parsing and validating JSON request body and JSON responding. The parser is compatible with any framework that exposes the HTTP interface like go-chi. Under the hood, the library uses go-json for JSON encoding/decoding and go-validator for validation.

Install

go get -u github.com/akhilmhdh/http-jparser

Features

  • Simple API
  • Request body validation
  • Compatibility with net/http
  • Uses go-json for fast encoding/decoding JSON

Examples

The following examples uses go-chi


package main

import (
	"net/http"

	jparser "github.com/akhilmhdh/http-jparser"
	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
)

type Response struct {
	HTTPStatusCode int         `json:"-"`               // http response status code
	Success        bool        `json:"success"`         // flag to indicated failed to success
	Message        string      `json:"message"`         // user-level status message
	AppCode        int64       `json:"code,omitempty"`  // application-specific error code
	ErrorText      interface{} `json:"error,omitempty"` // application-level error message, for debugging
	Data           interface{} `json:"data,omitempty"`
}

func (e *Response) GetStatusCode() int {
	return e.HTTPStatusCode
}

type ReqBody struct {
	Key   string `json:"key" validate:"lowercase"`
	Value string `json:"value"`
}

func main() {
	r := chi.NewRouter()
	r.Use(middleware.Logger)
	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		body := &Response{
			HTTPStatusCode: 200,
			Success:        true,
			Message:        "Success Request Message",
		}

		jparser.Send(w, r, body)
	})

	r.Post("/", func(w http.ResponseWriter, r *http.Request) {
		data := &ReqBody{}

		// GET JSON request body
		if err := jparser.Get(r, data); err != nil {
			// To check if error is validation error or not
			// if vErr, ok := err.(*jparser.ValidationErrors); ok {}
			// ErrInvalidRequest can be a wrapper on Response to return error messages
			jparser.Send(w, r, ErrInvalidRequest())
			return
		}

		// success response
		jparser.Send(w, r, &Response{
			HTTPStatusCode: 200,
			Message:        "Data returned successfully",
			Success:        true,
			Data:           data,
		})
	})

	http.ListenAndServe(":3000", r)
}

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrValidatorError  = errors.New("VALIDATION ERROR")
	ErrJSONEncodingErr = ""
)

Functions

func Get

func Get(r *http.Request, v interface{}) (err error)

Get function is used to get the JSON request body from http.Request object After decoding request body validation is triggered using govalidator

func Send

func Send(w http.ResponseWriter, r *http.Request, v Response) (err error)

Send function is used to send JSON. The response must have a method that returns status code The struct can be something like a generalized return body

func SendWithStatusCode

func SendWithStatusCode(w http.ResponseWriter, r *http.Request, v interface{}, status int) (err error)

SendWithStatusCode function is used to send JSON with a status code instead of method.

Types

type FieldError

type FieldError struct {
	Field     string `json:"field"`
	Err       string `json:"error"`
	FieldType string `json:"field_type"`
}

type Response

type Response interface {
	GetStatusCode() int
}

type ValidationErrors

type ValidationErrors []FieldError

ValidationErrors contains various validation errors happened to each field in an json object

func (*ValidationErrors) Error

func (v *ValidationErrors) Error() string

Jump to

Keyboard shortcuts

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