httpserver

package module
v0.0.0-...-51ff83b Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2019 License: MIT Imports: 10 Imported by: 0

README

httpserver

雑に HTTP サーバーを起動するやつ

Example

package main

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

	"github.com/thamaji/httpserver"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		logger, _ := httpserver.GetLogger(r)
		logger.Println("Hello!!")

		fmt.Fprintln(w, "Hello!!")
	})

	server := httpserver.New(
		mux,
		httpserver.WithPort(8080),
		httpserver.WithGracefulShutdown(30*time.Second, os.Interrupt, syscall.SIGTERM),
		httpserver.WithLogger(httpserver.DefaultLogger),
		httpserver.WithAccessLog(httpserver.DefaultLogFormatter),
		httpserver.WithRecoverer(httpserver.DefaultRecoverer),
	)

	if err := server.ListenAndServe(); err != nil {
		fmt.Println(err)
		return
	}
}

Documentation

Index

Constants

View Source
const LoggerContextKey ckLogger = 1

Variables

This section is empty.

Functions

func DefaultLogFormatter

func DefaultLogFormatter(ctx *LogContext) string

func DefaultRecoverer

func DefaultRecoverer(w http.ResponseWriter, r *http.Request, v interface{}, stak []byte)

Types

type LogContext

type LogContext struct {
	Request    *http.Request
	StatusCode int
	Size       uint64
	Duration   time.Duration
}

type LogFormatter

type LogFormatter func(*LogContext) string

type Logger

type Logger interface {
	Println(...interface{})
}
var DefaultLogger Logger = log.New(os.Stderr, "", log.LstdFlags)

func GetLogger

func GetLogger(r *http.Request) (Logger, bool)

type Option

type Option func(*Server) *Server

func WithAccessLog

func WithAccessLog(logFormatter LogFormatter) Option

func WithGracefulShutdown

func WithGracefulShutdown(timeout time.Duration, sig ...os.Signal) Option

func WithIdleTimeout

func WithIdleTimeout(timeout time.Duration) Option

func WithLogger

func WithLogger(logger Logger) Option

func WithPort

func WithPort(port int) Option

func WithReadHeaderTimeout

func WithReadHeaderTimeout(timeout time.Duration) Option

func WithReadTimeout

func WithReadTimeout(timeout time.Duration) Option

func WithRecoverer

func WithRecoverer(recoverer Recoverer) Option

func WithTLS

func WithTLS(certFile, keyFile string) Option

func WithWriteTimeout

func WithWriteTimeout(timeout time.Duration) Option

type Recoverer

type Recoverer func(http.ResponseWriter, *http.Request, interface{}, []byte)

type Server

type Server struct {
	// contains filtered or unexported fields
}

func New

func New(handler http.Handler, options ...Option) *Server

func (*Server) ListenAndServe

func (server *Server) ListenAndServe() error

Jump to

Keyboard shortcuts

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