Help us shape the future of Go! Take the 2026 Go Developer Survey

httpjson

package module
v0.0.0-...-3f624a0 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2019 License: MIT Imports: 3 Imported by: 0

README

go-httpjson

GoDoc

This repository provides useful functions to deal with JSON requests via HTTP.

Getting Started

ValidateAndDecode

ValidateAndDecode first checks HTTP request method and header, then decodes JSON body to struct.

ValidateAndDecode returns both error and corresponded StatusCode. When validation or decode fails, the StatusCode has corresponded error code. The StatusCode can be set as a status code for a HTTP response. StatusCode is set to http.StatusOK if the both of them are success.

type User struct {
	Name string `json:"text"`
	Age int `json:"int"`
}

func handleUser(w http.ResponseWriter, r *http.Request) {
	var user User
	err, statusCode := httpjson.ValidateAndDecode(r, &user)
	if err != nil {
		log.Printf(err.Error())
		w.WriteHeader(statusCode)
		return
	}
	log.Printf("Request: %v", user)
}
WriteResponse

WriteResponse writes StatusCode and JSON body to response. It also sets Content-Type header to application/json.

type User struct {
	Name string `json:"text"`
	Age int `json:"int"`
}

func handleUser(w http.ResponseWriter, r *http.Request) {
	user := User{Name: "NAME", Age: "Age"}
	err := httpjson.WriteResponse(w, http.StatusOK, &user)
	if err != nil {
		log.Printf(err.Error())
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Decode

func Decode(req *http.Request, v interface{}) error

func Validate

func Validate(req *http.Request) (error, int)

Validate checks HTTP request method and header. Validate returns both error and corresponded StatusCode when validation fails. The StatusCode can be set as a status code for a HTTP response.

func ValidateAndDecode

func ValidateAndDecode(req *http.Request, v interface{}) (error, int)

func WriteResponse

func WriteResponse(w http.ResponseWriter, statusCode int, v interface{}) error

WriteResponse writes StatusCode and JSON body to response. It also sets Content-Type header to application/json.

Types

This section is empty.

Jump to

Keyboard shortcuts

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