This toolkit package provides a set of utilities designed for the Go programming language to handle common tasks like generating random strings and handling file uploads in web applications.
The included tools are:
- Read JSON
- Write JSON
- Produce a JSON encoded error response
- Write XML
- Read XML
- Produce XML encoded error response
- Upload files via HTTP requests with optional renaming and file type validation.
- 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
To install the package, use the following command:
go get github.com/rozdolsky33/toolkit
Before using the package, import it in your Go project:
import "github.com/rozdolsky33/toolkit"
Create an instance of the Tools
type to access its methods:
tools := toolkit.Tools{
MaxFileSize: 1024 * 1024 * 1024, // 1 GB
AllowedFileTypes: []string{"image/jpeg", "image/png"},
}
Use the RandomString
method to generate a random string of specified length:
randomStr := tools.RandomString(16)
fmt.Println("Random String:", randomStr)
Use the UploadFiles
method to handle file uploads from HTTP requests. You can also specify whether to rename the uploaded files or not:
func uploadHandler(w http.ResponseWriter, r *http.Request) {
uploadDir := "./uploads"
uploadedFiles, err := tools.UploadFiles(r, uploadDir, true)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
for _, file := range uploadedFiles {
fmt.Fprintf(w, "Uploaded File: %s (original: %s), Size: %d bytes\n",
file.NewFileName, file.OriginalFileName, file.FileSize)
}
}
In your main function, set up the HTTP server to use this handler:
http.HandleFunc("/upload", uploadHandler)
http.ListenAndServe(":8080, nil)
The Tools
struct is used to instantiate the toolkit. This struct holds configuration for file uploads and JSON operations.
MaxFileSize int
: Maximum allowed file size for uploads (in bytes).AllowedFileTypes []string
: List of allowed file MIME types for validation.MaxJSONSize int
: Maximum allowed JSON size in bytes.AllowUnknownFields bool
: Flag to allow unknown JSON fields.
The UploadedFile
struct holds information about the uploaded files.
NewFileName string
: The name of the file saved on the server.OriginalFileName string
: The original name of the uploaded file.FileSize int64
: The size of the uploaded file in bytes.
The JSONResponse
struct is used to format JSON responses.
Error bool
: Indicates if the response is an error.Message string
: The message to be included in the response.Data interface{}
: Optional data payload.
Generates a random string of specified length n
.
func (t *Tools) RandomString(n int) string
Handles file uploads from HTTP requests, validates file type and optionally renames files.
func (t *Tools) UploadFiles(r *http.Request, uploadDir string, rename ...bool) ([]*UploadedFile, error)
r *http.Request
: The HTTP request object.uploadDir string
: Directory path where files will be uploaded.rename ...bool
: Optional boolean to specify whether to rename uploaded files.
Creates a directory if it does not exist.
func (t *Tools) CreateDirIfNotExist(dir string) error
dir string
: The directory path.
Transforms an input string into a URL-friendly slug.
func (t *Tools) Slugify(s string) (string, error)
s string
: The input string to be slugified.
Downloads a file and tries to force the browser to avoid displaying it in the browser window by setting content disposition.
func (t *Tools) DownloadStaticFile(w http.ResponseWriter, r *http.Request, p, file, displayName string)
w http.ResponseWriter
: The HTTP response writer.r *http.Request
: The HTTP request.p string
: The file path.file string
: The filename.displayName string
: The display name.
Reads and decodes JSON from a request body.
func (t *Tools) ReadJSON(w http.ResponseWriter, r *http.Request, data interface{}) error
w http.ResponseWriter
: The HTTP response writer.r *http.Request
: The HTTP request.data interface{}
: The target data structure.
Encodes data as JSON and writes it to the response.
func (t *Tools) WriteJSON(w http.ResponseWriter, status int, data interface{}, headers ...http.Header) error
w http.ResponseWriter
: The HTTP response writer.status int
: The HTTP status code.data interface{}
: The payload to be encoded as JSON.headers ...http.Header
: Optional headers.
Generates and sends a JSON error response.
func (t *Tools) ErrorJSON(w http.ResponseWriter, err error, status ...int) error
w http.ResponseWriter
: The HTTP response writer.err error
: The error to be included in the response.status ...int
: Optional HTTP status code.
Sends the given data as a JSON payload to a specified URI via HTTP POST using an optional custom HTTP client.
func (t *Tools) PushJSONToRemote(uri string, data interface{}, client ...*http.Client) (*http.Response, int, error)
uri string
: The target URI.data interface{}
: The data to be sent as JSON.client ...*http.Client
: Optional custom HTTP client.