server

package module
v2.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 18, 2024 License: BSD-3-Clause Imports: 14 Imported by: 0

README

http-server - HTTP Routing, Logging & Telemetry

Documentation

Official godoc documentation (with examples) can be found at the Package Registry.

Usage

Add Package Dependency
go get -u github.com/x-ethr/go-http-server/v2
Import & Implement

main.go

package main

import (
    "context"
    "encoding/json"
    "errors"
    "fmt"
    "log/slog"
    "net/http"
    "os"

    "github.com/x-ethr/go-http-server/v2"
    "github.com/x-ethr/go-http-server/v2/writer"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())

    mux := http.NewServeMux()

    mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
        var response = map[string]interface{}{
            "key": "value",
        }

        w.WriteHeader(http.StatusOK)
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(response)
    })

    // Add Response Writer
    handler := writer.Handle(mux)

    // Start the HTTP server
    slog.Info("Starting Server ...", slog.String("local", fmt.Sprintf("http://localhost:%s", "8080")))

    api := server.Server(ctx, handler, "8080")

    // Issue Cancellation Handler
    server.Interrupt(ctx, cancel, api)

    // <-- Blocking
    if e := api.ListenAndServe(); e != nil && !(errors.Is(e, http.ErrServerClosed)) {
        slog.ErrorContext(ctx, "Error During Server's Listen & Serve Call ...", slog.String("error", e.Error()))

        os.Exit(100)
    }

    // --> Exit
    {
        slog.InfoContext(ctx, "Graceful Shutdown Complete")

        // Waiter
        <-ctx.Done()
    }
}

Contributions

See the Contributing Guide for additional details on getting started.

Documentation

Overview

Package server - HTTP Server.

Example
ctx, cancel := context.WithCancel(context.Background())

mux := http.NewServeMux()

mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
	var response = map[string]interface{}{
		"key": "value",
	}

	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
})

// Add Response Writer
handler := writer.Handle(mux)

// Start the HTTP server
slog.Info("Starting Server ...", slog.String("local", fmt.Sprintf("http://localhost:%s", "8080")))

api := server.Server(ctx, handler, "8080")

// Issue Cancellation Handler
server.Interrupt(ctx, cancel, api)

// <-- Blocking
if e := api.ListenAndServe(); e != nil && !(errors.Is(e, http.ErrServerClosed)) {
	slog.ErrorContext(ctx, "Error During Server's Listen & Serve Call ...", slog.String("error", e.Error()))

	os.Exit(100)
}

// --> Exit
{
	slog.InfoContext(ctx, "Graceful Shutdown Complete")

	// Waiter
	<-ctx.Done()
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var Health http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
	response := map[string]string{
		"status": "ok",
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)

	json.NewEncoder(w).Encode(response)

	return
}

Functions

func Interrupt

func Interrupt(ctx context.Context, cancel context.CancelFunc, server *http.Server)

Interrupt is a graceful interrupt + signal handler for an HTTP server.

func Server

func Server(ctx context.Context, handler http.Handler, port string) *http.Server

Server initializes a http.Server.

Types

type Helper added in v2.0.5

type Helper interface {
	Help() Validators // Help is a method of the Helper interface that returns a map of string keys to Validator values.
}

Helper is an interface that defines a single method, Help(). Help() returns a map of string keys to Validator values, representing validation checks for specific fields.

type Validator added in v2.0.5

type Validator struct {
	Value   interface{} `json:"value,omitempty"` // Value is the value that was validated.
	Valid   bool        `json:"valid"`           // Valid is a boolean field indicating whether the validation check was successful or not.
	Message string      `json:"message"`         // Message is a field in the Validator struct that holds an optional message providing additional information about the validation result.
}

Validator is a type that represents a validation result for a specific field. It contains information about the validated value, validity, and an optional message.

  • The [Validator.Value] field stores the value that was validated.
  • The [Validator.Valid] field indicates whether the validation check was successful or not.
  • The [Validator.Message] field holds an optional message providing additional information about the validation result.

type Validators added in v2.0.5

type Validators map[string]Validator

Validators is a type that represents a map of string keys to Validator values. Each key-value pair in the map corresponds to a validation check for a specific field. The string key is the field name, and the Validator value contains information about the validation result.

func Validate added in v2.0.5

func Validate(ctx context.Context, v *validator.Validate, body io.Reader, data interface{}) (Validators, error)

Validate is a function that takes a context, validator, request body reader, and data interface as arguments. It performs the following steps: 1. Unmarshals the request body into the data interface. 2. Validates the data using the validator. 3. If there are validation errors, logs each error and returns an appropriate response. 4. If the data implements the Helper interface, returns the result of the Help method. 5. Logs the data for debugging purposes. 6. Returns nil if there were no exceptions generated. The function returns a string message, a map of Validators, and an error.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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