Skip to content

jeff-mcintire/go-toolkit

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Web Toolkit for Go

A simple example of how to create a reusable Go module with commonly used tools.

The included tools are:

  • Read JSON
  • Write JSON
  • Produce a JSON encoded error response
  • Upload a file of files to a specified directory
  • Download a static file
  • Get a random string of length n
  • Post JSON to a remote service
  • Create a directory, including all parent directories, if it does not already exist
  • Create a URL safe slug from a string

Function Notes

Name: Slugify
Input(s): String
Output(s): String with any special character stripped out and spaces replaced by dashes
Sample: slug, err := tool.Slugify("string")

Name: CreateDirIfNotExist
Notes: accepts a string, parses it and creates a directory and any parent directories if they do not exist.
Sample: err := tool.CreateDirIfNotExist("./testdata/myDir")

Name: RandomString
Notes: accepts an int and returns a random string of int length.
Sample: s := tool.RandomString(10)

Name: DownloadStaticFile
Notes: forces a file to be downloaded and not displayed in a browser.
Sample: tool.DownloadStaticFile(rr, req, "./testdata/pic.jpg", "puppy.jpg")

Name: UploadFiles
Notes: Multi file uploader
Sample: uploadedFiles, err := testTools.UploadFiles(request, "./testdata/uploads/", e.renameFile)

Name: UploadOneFile
Notes: Helper function that will upload one file
Sample: uploadedFiles, err := testTools.UploadOneFile(request, "./testdata/uploads/", true)

Name: ReadJSON
Notes: tries to read the body of a request and converts from json into a go data variable
Sample: err = testTool.ReadJSON(rr, req, &decodedJSON)

Name: WriteJSON
Notes: takes a response status code and arbitrary data and writes json to the client
Sample: err := testTools.WriteJSON(rr, http.StatusOK, payload, headers)

Name: ErrorJSON
Notes: takes an error, & optionally a status code, and generates and sends a JSON error message
Sample: err := testTools.ErrorJSON(rr, errors.New("some error"), http.StatusServiceUnavailable)

Name: PushJSONToRemote
Notes: posts arbitrary data to some URL as JSON, and returns the response, status code, and error, if any.
Sample: _, _, err := testTools.PushJSONToRemote("http://example.com/some/path", foo, client)

Installation

go get github.com/jeff-mcintire/go-toolkit/