package
0.10.4
Repository: https://github.com/useinsider/go-pkg.git
Documentation: pkg.go.dev

# README

Simple Route Package

This package is designed to provide a simple way to create HTTP routes in your application. It provides a clean and flexible API for integrating into your codebase.

Usage in Apps

package main

import (
	"context"
	"fmt"
	"net/http"
	"strings"

	"github.com/useinsider/go-pkg/inssimpleroute"
)

// Request type for the use case
type GreetingRequest struct {
	Name string `json:"name"`
}

// Response type for the use case
type GreetingResponse struct {
	Message string `json:"message"`
}

// GreetingUseCase is the core business logic for generating a greeting message
func GreetingUseCase(ctx context.Context, request *GreetingRequest) (*GreetingResponse, error) {
	// Generate a greeting message
	greeting := fmt.Sprintf("Hello, %s!", strings.TrimSpace(request.Name))
	response := &GreetingResponse{
		Message: greeting,
	}
	return response, nil
}

// GreetingRequestDecoder is a custom decoder for GreetingRequest
func GreetingRequestDecoder(_ context.Context, r *http.Request) (*GreetingRequest, error) {
	var request GreetingRequest
	if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
		return nil, err
	}
	return &request, nil
}

func main() {
	// Create a new server route with the GreetingUseCase and a request decoder
	server := inssimpleroute.NewServerWithDefaults(GreetingUseCase, GreetingRequestDecoder)

	// Register the server route
	http.Handle("/greet", server)

	// Start the HTTP server
	port := 8080
	addr := fmt.Sprintf(":%d", port)
	fmt.Printf("Server listening on %s\n", addr)
	err := http.ListenAndServe(addr, nil)
	if err != nil {
		fmt.Printf("Error: %s\n", err)
	}
}

# Functions

DefaultErrorEncoder writes the error to the ResponseWriter, by default a content type of text/plain, a body of the plain text of the error, and a status code of 500.
EncodeJSONResponse is a EncodeResponseFunc that serializes the response as a JSON object to the ResponseWriter.
NewServer constructs a new server, which implements http.HttpHandler and wraps the provided endpoint.
NewServerWithDefaults constructs a new server, which implements http.HttpHandler and wraps the provided endpoint.

# Structs

SimpleRoute wraps an endpoint and implements http.HttpHandler.

# Interfaces

Headerer is checked by DefaultErrorEncoder.
StatusCoder is checked by DefaultErrorEncoder.

# Type aliases

CreateRequestFunc creates an outgoing HTTP request based on the passed request object.
DecodeRequestFunc extracts a user-domain request object from an HTTP request object.
DecodeResponseFunc extracts a user-domain response object from an HTTP response object.
EncodeRequestFunc encodes the passed request object into the HTTP request object.
EncodeResponseFunc encodes the passed response object to the HTTP response writer.
ErrorEncoder is responsible for encoding an error to the ResponseWriter.
No description provided by the author