GoHttpService

package module
v0.0.0-...-66b0c4e Latest Latest
Warning

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

Go to latest
Published: Jun 10, 2016 License: MIT Imports: 9 Imported by: 0

README

Go HttpService

HTTP methods I use a lot.

Basic HTTP Responses

This package offers a simple structure for sending back basic HTTP responses. This structure has two keys: Success and Message. To create a message one can use the method NewBasicJsonResponse() like so.

import (
    "github.com/adampresley/GoHttpService"
)

func DoSomething() {
    response := GoHttpService.NewBasicJsonResponse(true, "Everything worked great")
}

There are simplier methods for the most common operations such as responding with an error or success. The following samples illustrate these.

import (
    "net/http"

    "github.com/adampresley/GoHttpService"
)

/*
{ "success": false, "message": "An error occurred" }
*/
func AnError(writer http.ResponseWriter, request *http.Request) {
    GoHttpService.Error(writer, "An error occurred")
}

/*
{ "success": false, "message": "Bad request sir!" }
*/
func BadRequest(writer http.ResponseWriter, request *http.Request) {
    GoHttpService.BadRequest(writer, "Bad request sir!")
}

/*
{ "success": false, "message": "Not found!" }
*/
func NotFound(writer http.ResponseWriter, request *http.Request) {
    GoHttpService.NotFound(writer, "Not found!")
}

/*
{ "success": true, "message": "Everything is awesome!" }
*/
func NotFound(writer http.ResponseWriter, request *http.Request) {
    GoHttpService.Success(writer, "Everything is awesome!")
}

Writing Arbitrary Data

Very often you'll need to write some arbitrary structure out as a response. Here is an example of doing that.

type Something struct {
    Id int `json:"id"`
    Name string `json:"name"`
}

/*
{ "id": 1, "name": "Bob" }
*/
func Arbitrary(writer http.ResponseWriter, request *http.Request) {
    result := Something{Id: 1, Name: "Bob"}
    GoHttpService.WriteJson(writer, result, 200)
}

Parsing Information

Below are examples of functions for parsing data.

type Something struct {
    Id int `json:"id"`
    Name string `json:"name"`
}

/*
With a body of:

{"id": 2, "name": "Adam"}

result will be filled in with values from the parsed body
*/
func ParseJsonInBodySample(writer http.ResponseWriter, request *http.Request) {
    result := Something{}
    GoHttpService.ParseJsonBody(request, &result)
}

Tests

To run the tests open a terminal and execute the following.

$ go test -v

License

The MIT License (MIT)

Copyright (c) 2014 Adam Presley

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BadRequest

func BadRequest(writer http.ResponseWriter, message string)

Convenience method sending out a BasicJsonResponse in JSON format with a success of FALSE. This will set the HTTP status code to 400. This is useful for telling a caller that the request is malformed.

func Error

func Error(writer http.ResponseWriter, message string)

Convenience method sending out a BasicJsonResponse in JSON format with a success of FALSE. This will set the HTTP status code to 500. This is useful for indicating some type of error ocurred during processing.

func Forbidden

func Forbidden(writer http.ResponseWriter, message string)

Convenience method sending our a BasicJsonResponse in JSON format with a success of FALSE. This will set the HTTP status code to 403. This is useful in telling a caller that some type of authentication failed.

func LoadHtml

func LoadHtml(pageName string) ([]byte, error)

func NotFound

func NotFound(writer http.ResponseWriter, message string)

Convenience method sending out a BasicJsonResponse in JSON format with a success of FALSE. This will set the HTTP status code to 404. This is useful in telling a caller that the resources they are trying to get is not found.

func ParseJsonBody

func ParseJsonBody(request *http.Request, receiver interface{}) error

This function is useful when a POST or PUT request has a Content-Type of application/json and the body has JSON data. Pass the address of a receiver variable and this function will fill in the values from the request JSON into any matching struct fields, or will hydrate them into a map if possible.

func RenderHtml

func RenderHtml(writer http.ResponseWriter, pageName string) error

func RenderTemplate

func RenderTemplate(writer http.ResponseWriter, pageName string, data interface{}) error

func RequestIsJsonContentType

func RequestIsJsonContentType(request *http.Request) bool

Returns true/false if the request contains a Content-Type header, and if that header is set to "application/json".

func SessionExpired

func SessionExpired(writer http.ResponseWriter)

Convenience method for telling clients that a session has expired. This sends a SessionExpiredResponse structure and a status of 401 Unauthorized.

func SplitListOfIntsInURL

func SplitListOfIntsInURL(request *http.Request, key string, delimiter string) []int

SplitListOfIntsInURL takes a delimited list value in a URL key and splits it into a slice of integers

func Success

func Success(writer http.ResponseWriter, message string)

Convenience method sending out a BasicJsonResponse in JSON format with a success of TRUE. This will set the HTTP status code to 200.

func WriteHTML

func WriteHTML(writer http.ResponseWriter, html string, code int)

func WriteJson

func WriteJson(writer http.ResponseWriter, object interface{}, code int)

This function serializes an object to JSON and writes it to the specified writer stream with an HTTP code. The object is of type interface{} so can technically be anything. A struct or map would be the usual type of item to serialize.

func WriteText

func WriteText(writer http.ResponseWriter, text string, code int)

Types

type BasicJsonResponse

type BasicJsonResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
}

func NewBasicJsonResponse

func NewBasicJsonResponse(success bool, message string) BasicJsonResponse

Creates a new BasicJsonResponse structure.

type Layout

type Layout struct {
	BaseDirectory     string
	TemplateFileNames []string
	TemplateBodies    map[string]string
}

func NewLayout

func NewLayout(baseDirectory string, templateFileNames []string) (Layout, error)

func (Layout) RenderView

func (this Layout) RenderView(writer http.ResponseWriter, pageName string, data interface{}) error

type SessionExpiredResponse

type SessionExpiredResponse struct {
	Success        bool `json:"success"`
	SessionExpired bool `json:"sessionExpired"`
}

func NewSessionExpiredResponse

func NewSessionExpiredResponse() SessionExpiredResponse

Creates a new SessionExpiredResponse structure.

Jump to

Keyboard shortcuts

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