Skip to content

kube-land/rest-util1

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

rest-util

GoDoc Go Report Card Coverage

The rest-util is a small library for handling RESTful JSON response and status messages. It could be used by any RESTful API easily to convert any structure to JSON response message and write to ResponseWriter.

Usage

package main

import (
    "net/http"
    "github.com/pharmatics/rest-util"
)

type User struct {
    Name string `json:"name,omitempty"`
    Age  int    `json:"age,omitempty"`
}

func main() {
    http.HandleFunc("/success", UserSuccess)
    http.HandleFunc("/failure", UserFailure)
    http.ListenAndServe(":8080", nil)
}

func UserSuccess(w http.ResponseWriter, r *http.Request) {
    user := User{
        Name: "Alice",
        Age: 23,
    }
    restutil.ResponseJSON(user, w, 200)
}

func UserFailure(w http.ResponseWriter, r *http.Request) {
    user := User{
        Name: "Alice",
        Age: 23,
    }
    status := restutil.ErrorWithDetails("Can't process user", restutil.StatusReasonInvalid, user)
    restutil.ResponseJSON(status, w, status.Code)
}

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages