webh

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: May 21, 2024 License: GPL-3.0 Imports: 17 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

License

webh, the web helper for Golang

Include web code snippets for speed up the development.

This is a tiny yet powerful library was built for do not write every single time the web server.

We provide several capabilities used in the industry like middlewares, graceful shutdown, logging, ability to unwrap web handlers that return an error in order to avoid weird returns.

A clean mechanism to log errors among the http requests.

Encoder and Decoder for JSON.

A custom error type for web purposes.

The Server is created on top of chi web library, so will have all the same features and ways to declare endpoints.

Heartbeat at /ping is already declared for you, among recover and logger. Do not worry to add them.

Installation
go get -u github.com/tomiok/webh
Create and start the server with one endpoint.
s := webh.NewServer("8080", webh.WithLogger("hello"), webh.WithHeartbeat("/ping"))

s.Get("/hello", func(w http.ResponseWriter, r *http.Request){
	//.....
})

s.Start()

or use a custom handler returning an error.

package web

import (
	"fmt"
	"net/http"
)

func HelloHandler(w http.ResponseWriter, r *http.Request) error {
	_, err := fmt.Fprint(w, "hello")
	return err
}
package main

import "github.com/tomiok/webh"

func main() {
	s := webh.NewServer("8080", webh.WithLogger("hello"), webh.WithHeartbeat("/ping"))

	s.Get("/hello", webh.Unwrap(HelloHandler))

	s.Start()
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DJson

func DJson[t any](b io.ReadCloser, target *t) (*t, error)

DJson is a generic way to unmarshal your JSON.

func EJson

func EJson(w io.Writer, v any) error

EJson is the shorthand to encode JSON.

func Res

func Res(status int, w http.ResponseWriter, data any)

Res is a wrapper for web handlers that are compliant with the stdlib signature but returning an error.

func ResErr

func ResErr(status int, w http.ResponseWriter, data any) error

ResErr is a wrapper for web handlers that are compliant with the stdlib signature but returning an error.

func Response

func Response(status int, w http.ResponseWriter, msg string, data any)

Response is a wrapper for web handlers that are compliant with the stdlib.

func ResponseErr

func ResponseErr(status int, w http.ResponseWriter, msg string, data any) error

ResponseErr is a wrapper for web handlers that are compliant with the stdlib signature but returning an error.

func Unwrap

func Unwrap(h WebHandler) http.HandlerFunc

Types

type CorsOpt added in v0.1.2

type CorsOpt struct {
	AllowedOrigins []string
	AllowedHeaders []string
	ExposedHeaders []string

	AllowCredentials bool
	MaxAge           int
}

type ErrHTTP

type ErrHTTP struct {
	Message string
	Code    int
}

func (ErrHTTP) Error

func (e ErrHTTP) Error() string

type HttpResponse

type HttpResponse struct {
	Message   string `json:"message"`
	Data      any    `json:"data,omitempty"`
	Success   bool   `json:"success"`
	RequestID string `json:"request_id,omitempty"`
}

type Option added in v0.1.2

type Option func(options *options)

func WithCompress added in v0.1.2

func WithCompress(level int, types ...string) Option

WithCompress you can add a compress middleware. NOTE: make sure to set the Content-Type header on your response otherwise this middleware will not compress the response body. For ex, in your handler you should set w.Header().Set("Content-Type", http.DetectContentType(yourBody)) or set it manually.

Passing a compression level of 5 is sensible value

func WithCors added in v0.1.2

func WithCors(opt CorsOpt, allowedMethods ...string) Option

WithCors add cors to your web server. AllowedMethods example {"GET", "POST", "PUT", "DELETE", "OPTIONS"}.

func WithHeartbeat added in v0.1.2

func WithHeartbeat(path string) Option

WithHeartbeat add a dummy endpoint in the specified path. Will return a non-json response "." with a 200 status.

func WithRequestLogger added in v0.1.2

func WithRequestLogger(serviceName string, loggerOptions ...httplog.Options) Option

WithRequestLogger add a JSON logger to your web server.

type Server

type Server struct {
	*chi.Mux
	// contains filtered or unexported fields
}

func NewServer

func NewServer(port string, serverOptions ...Option) *Server

NewServer return a *Server. Including Logger will include also recoverer and requestID middlewares.

func (*Server) FileServer added in v0.1.2

func (s *Server) FileServer(path string)

FileServer will be used to serve the static files, please specify the route.

func (*Server) Start

func (s *Server) Start()

Start runs ListenAndServe on the http.Server with graceful shutdown.

type WebHandler

type WebHandler func(w http.ResponseWriter, r *http.Request) error

Jump to

Keyboard shortcuts

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