httpserver

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2023 License: MIT Imports: 18 Imported by: 0

README

HTTPServer

The httpserver package implements the core functionality of a coder-based http server.

Getting Started

package main

import (
	"encoding/json"
	"net/http"

	"github.com/gromey/proton/coder"
	"github.com/gromey/proton/httpserver"
)

func main() {
	cdrJSON := coder.NewCoder("application/json", json.Marshal, json.Unmarshal)

	fmtJSON := httpserver.NewFormatter(cdrJSON)

	handlerFunc := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodGet {
			req := &struct {
				// some fields
			}{}

			if err := fmtJSON.Decode(r.Body, req); err != nil {
				panic(err)
			}
		}

		res := &struct {
			ID int `json:"id"`
		}{ID: 1}

		fmtJSON.WriteResponse(w, http.StatusOK, res)
	})

	http.Handle("/example/", handlerFunc)

	if err := http.ListenAndServe(":8080", nil); err != nil {
		panic(err)
	}
}

For all responses with a body:
  • The default is to use the Content-Type set in the coder.
  • If you don't set the Content-Type in the coder, it will be set automatically by the net/http package.
  • If you need to set a different Content-Type you must set it before calling WriteResponse.
For all responses without a body:
  • Content-Type will not be set by default.
  • If you need to set Content-Type you must set it before calling WriteResponse.
package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gromey/proton/httpserver"
)

func main() {
	handlerFunc := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
		_, _ = fmt.Fprint(w, "Hello!")
	})

	handler := http.NewServeMux()
	handler.HandleFunc("/example/", handlerFunc)

	srv := new(http.Server)
	srv.Addr = ":8080"
	srv.Handler = handler

	hcr := new(httpserver.Controller)
	hcr.Server = srv
	hcr.GracefulTimeout = time.Second * 10

	if err := hcr.Start(); err != nil {
		panic(err)
	}
}

The httpserver package contains functions that are used as middleware on the http server side.

Getting Started

package main

import (
	"fmt"
	"net/http"

	"github.com/gromey/proton/httpserver"
	"github.com/gromey/proton/logger"
)

func main() {
	handlerFunc := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if _, err := fmt.Fprintln(w, "Hello World!"); err != nil {
			panic(err)
		}
	})

	http.Handle("/example/", handlerFunc)

	handler := httpserver.MiddlewareSequencer(
		http.DefaultServeMux,
		httpserver.DumpHttp(logger.LevelTrace),
		httpserver.Timer(logger.LevelInfo),
		httpserver.PanicCatcher,
	)

	if err := http.ListenAndServe(":8080", handler); err != nil {
		panic(err)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllowCORS

func AllowCORS(next http.Handler, opts *CORSOptions) http.Handler

AllowCORS sets headers for CORS mechanism supports secure.

func DumpHttp

func DumpHttp(logLevel logger.Level) func(http.Handler) http.Handler

DumpHttp dumps the HTTP request and response, and prints out with logFunc.

func MiddlewareSequencer

func MiddlewareSequencer(baseHandler http.Handler, mws ...func(http.Handler) http.Handler) http.Handler

MiddlewareSequencer chains middleware functions in a chain.

func PanicCatcher

func PanicCatcher(next http.Handler) http.Handler

PanicCatcher handles panics in http.HandlerFunc.

func Timer

func Timer(logLevel logger.Level) func(http.Handler) http.Handler

Timer measures the time taken by http.HandlerFunc.

Types

type CORSOptions

type CORSOptions struct {
	AllowedOrigins   []string // The origins that the server allows.
	AllowMethods     []string // List of methods that the server allows.
	AllowHeaders     []string // List of headers that the server allows.
	MaxAge           int      // Tells the browser how long (in seconds) to cache the response to the preflight request.
	AllowCredentials bool     // Allow browsers to expose the response to the external JavaScript code.
}

CORSOptions represents a functional option for configuring the CORS middleware.

type Controller

type Controller struct {
	Server          *http.Server
	GracefulTimeout time.Duration
	// contains filtered or unexported fields
}

Controller is a wrapper around *http.Server to control the server.

Server — *http.Server, which will be managed.
GracefulTimeout — time that is given to the server to shut down gracefully.

func (*Controller) Restart

func (c *Controller) Restart()

Restart restarts the server if necessary. For changes to the following parameters to take effect:

Addr; TLSConfig; TLSNextProto; ConnState; BaseContext; ConnContext,

a server restart is required. Other parameters can be changed without restarting the server. If the server is not running, the function will be skipped.

func (*Controller) Shutdown

func (c *Controller) Shutdown()

Shutdown gracefully shuts down the server.

func (*Controller) Start

func (c *Controller) Start() error

Start starts the *http.Server. If *tls.Config on the server is non nil, the server listens and serves using tls.

type Formatter

type Formatter interface {
	coder.Coder
	WriteResponse(w http.ResponseWriter, statusCode int, v any)
}

func NewFormatter

func NewFormatter(coder coder.Coder) Formatter

NewFormatter returns a new Formatter.

Jump to

Keyboard shortcuts

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