server

package
v0.0.96 Latest Latest
Warning

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

Go to latest
Published: May 3, 2024 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package server provides HTTP server implementation. The server provided in here is opinionated and comes with good defaults.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run(h http.Handler, o config.Opts) error

Run creates a http server, starts the server on a network address and then calls Serve to handle requests on incoming connections.

It sets up a server with the parameters provided by o. If the Opts supplied include a certificate and key, the server will accept https traffic and also automatically handle http->https redirect. Likewise, if the Opts include an acmeEmail address, the server will accept https traffic and automatically handle http->https redirect.

The server shuts down cleanly after receiving any termination signal.

Example
package main

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

	"github.com/komuw/ong/config"
	"github.com/komuw/ong/log"
	"github.com/komuw/ong/middleware"
	"github.com/komuw/ong/mux"
	"github.com/komuw/ong/server"
)

func main() {
	l := log.New(context.Background(), os.Stdout, 1000)
	secretKey := "super-h@rd-Pas1word"
	opts := config.WithOpts(
		"localhost",
		65081,
		secretKey,
		config.DirectIpStrategy,
		l,
	) // dev options.
	// alternatively for production:
	//   opts := config.LetsEncryptOpts(...)

	mx := mux.New(
		opts,
		nil,
		mux.NewRoute(
			"hello/",
			mux.MethodGet,
			hello("hello world"),
		),
		mux.NewRoute(
			"check/:age/",
			mux.MethodAll,
			check(),
		),
	)

	err := server.Run(mx, opts)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func hello(msg string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		cspNonce := middleware.GetCspNonce(r.Context())
		csrfToken := middleware.GetCsrfToken(r.Context())
		fmt.Printf("hello called cspNonce: %s, csrfToken: %s", cspNonce, csrfToken)

		// use msg, which is a dependency specific to this handler
		fmt.Fprint(w, msg)
	}
}

func check() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		age := mux.Param(r.Context(), "age")
		_, _ = fmt.Fprintf(w, "Age is %s", age)
	}
}
Output:

Types

This section is empty.

Jump to

Keyboard shortcuts

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