web

package module
v0.0.0-...-4512632 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2020 License: MIT Imports: 19 Imported by: 0

README

web

🕸 Your friendly neighborhood HTTP client and server

Download

$ go get -u -v github.com/picatz/web
...

Client Usage

package main

import (
  "fmt"

  "github.com/picatz/web"
)

func main() {
  client, _ := web.NewClient()

  resp, err := client.Get("https://www.google.com")

  if err != nil {
    panic(err)
  }

  fmt.Println(resp.StatusCode)
}

Server Usage

package main

import (
  "log"
  "net/http"
  "os"

  "github.com/picatz/web"
)

func main() {
  logger := log.New(os.Stderr, "example-web-server: ", log.LstdFlags)

  helloWorld := func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello World!"))
  }

  server, _ := web.NewServer(
    web.WithRoutes(
      web.Routes{"/": helloWorld},
      web.MiddlewareLogRequest(logger),
      web.MiddlewareLimitRequestBody(web.DefaultRequestBodySize),
    ),
  )

  web.Serve(server, nil, "", "")
}

Server Authentication

A simple Google Oauth2 authenticator implementation is built in. First you'll need to generate and export the following ENV variables:

$ export GOOGLE_OAUTH_CLIENT_ID="..."
$ export GOOGLE_OAUTH_CLIENT_SECRET="..."
package main

import (
  "html/template"
  "log"
  "net/http"
  "os"

  "github.com/picatz/web"
)

func main() {
  logger := log.New(os.Stderr, "test-web-server: ", log.LstdFlags)

  authenticator, _ := web.NewOauth2GoogleAuthenticator(
    web.WithRedirectToLoginOnAuthFailure(),
  )

  tmpl, _ := template.New("homePage").Parse(`
    <!DOCTYPE html>
    <html lang="en">
    <meta charset="utf-8">

    <body>
      Hello {{.}}

      <a href="/auth/google/logout">Logout</a>
    </body>
  `)

  helloWorld := func(w http.ResponseWriter, r *http.Request) {
    v, ok := authenticator.ReadSessionValue(w, r, "name")
    if ok {
      tmpl.Execute(w, v)
    }
  }

  mainRoutes := web.Routes{
    "/": helloWorld,
  }

  server, _ := web.NewServer(
    web.WithRoutes(
      web.JoinRoutes(
        web.AuthenticatedRoutes(authenticator, mainRoutes),
        authenticator.Routes(),
      ),
      web.MiddlewareLogRequest(logger),
    ),
  )

  web.Serve(server, nil, "", "")
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultServerReadTimeout  = 5 * time.Second
	DefaultServerWriteTimeout = 5 * time.Second
	DefaultServerIdleTimeout  = 10 * time.Second
)

Default server timeout values.

View Source
var DefaultRequestBodySize = int64(1024)
View Source
var DefaultServerTLSConfig = &tls.Config{
	MinVersion:               tls.VersionTLS12,
	CurvePreferences:         []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
	CipherSuites:             DefaultServerTLSConfigCipherSuites,
	PreferServerCipherSuites: true,
}

DefaultServerTLSConfig defines the default TLS configuration for a server.

DefaultServerTLSConfigCipherSuites contains TLS cipher configuration.

View Source
var DefaultServerTLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0)

DefaultServerTLSNextProto defines the default TLS protocol logic for a server.

Functions

func GenerateNewCookiStore

func GenerateNewCookiStore() *sessions.CookieStore

func GenerateNewRandKey

func GenerateNewRandKey() []byte

func NewClient

func NewClient(opts ...ClientOption) (*http.Client, error)

func NewServer

func NewServer(opts ...ServerOption) (*http.Server, error)

NewServer simplifies the creation of a new HTTP server using an optional list of ServerOptions for configuration.

func Serve

func Serve(s *http.Server, l *log.Logger, certFile, keyFile string)

Serve starts the listener.

Types

type Authenticator

type Authenticator interface {
	Routes() Routes
	RequireAuthentication(http.HandlerFunc) http.HandlerFunc
	IsAuthenticated(w http.ResponseWriter, r *http.Request) bool
	Authenticate(w http.ResponseWriter, r *http.Request)
	Deauthenticate(w http.ResponseWriter, r *http.Request)
	ReadSessionValue(w http.ResponseWriter, r *http.Request, key string) (interface{}, bool)
}

func NewOauth2GoogleAuthenticator

func NewOauth2GoogleAuthenticator(opts ...Oauth2GoogleOption) (Authenticator, error)

type ClientOption

type ClientOption = func(*http.Client) error

type Oauth2GoogleAuthenticator

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

func (*Oauth2GoogleAuthenticator) Authenticate

func (a *Oauth2GoogleAuthenticator) Authenticate(w http.ResponseWriter, r *http.Request)

func (*Oauth2GoogleAuthenticator) Deauthenticate

func (a *Oauth2GoogleAuthenticator) Deauthenticate(w http.ResponseWriter, r *http.Request)

func (*Oauth2GoogleAuthenticator) IsAuthenticated

func (a *Oauth2GoogleAuthenticator) IsAuthenticated(w http.ResponseWriter, r *http.Request) bool

func (*Oauth2GoogleAuthenticator) ReadSessionValue

func (a *Oauth2GoogleAuthenticator) ReadSessionValue(w http.ResponseWriter, r *http.Request, key string) (interface{}, bool)

func (*Oauth2GoogleAuthenticator) RequireAuthentication

func (a *Oauth2GoogleAuthenticator) RequireAuthentication(h http.HandlerFunc) http.HandlerFunc

func (*Oauth2GoogleAuthenticator) Routes

func (a *Oauth2GoogleAuthenticator) Routes() Routes

type Oauth2GoogleOption

type Oauth2GoogleOption func(*Oauth2GoogleAuthenticator) error

func WithAuthCallback

func WithAuthCallback(cb func(http.ResponseWriter, *http.Request) error) Oauth2GoogleOption

func WithAuthRedirectURL

func WithAuthRedirectURL(url string) Oauth2GoogleOption

func WithCookieStoreForOauth2Google

func WithCookieStoreForOauth2Google(givenStore *sessions.CookieStore) Oauth2GoogleOption

func WithRedirectOnAuthFailure

func WithRedirectOnAuthFailure(url string) Oauth2GoogleOption

func WithRedirectOnLogout

func WithRedirectOnLogout(url string) Oauth2GoogleOption

func WithRedirectToLoginOnAuthFailure

func WithRedirectToLoginOnAuthFailure() Oauth2GoogleOption

type RouteMiddleware

type RouteMiddleware func(http.HandlerFunc) http.HandlerFunc

func MiddlewareContentType

func MiddlewareContentType(contentType string) RouteMiddleware

func MiddlewareContentTypeJSON

func MiddlewareContentTypeJSON() RouteMiddleware

func MiddlewareContentTypeUTF8

func MiddlewareContentTypeUTF8(contentType string) RouteMiddleware

func MiddlewareHSTS

func MiddlewareHSTS() RouteMiddleware

func MiddlewareHeader

func MiddlewareHeader(headerKey, headerValue string) RouteMiddleware

func MiddlewareLimitRequestBody

func MiddlewareLimitRequestBody(numBytes int64) RouteMiddleware

func MiddlewareLogRequest

func MiddlewareLogRequest(logger *log.Logger) RouteMiddleware

func MiddlewareSSHProxy

func MiddlewareSSHProxy(sshAddr string, cfg *ssh.ClientConfig, remoteAddr string) RouteMiddleware

type Routes

type Routes = map[string]http.HandlerFunc

Routes contains a { key -> value } mapping of { pathString -> http.HandlerFunc }

func AuthenticatedRoutes

func AuthenticatedRoutes(a Authenticator, r ...Routes) Routes

AuthenticatedRoutes takes multiple Routes and requires them all to be authenticated.

func JoinRoutes

func JoinRoutes(r ...Routes) Routes

JoinRoutes takes multiple Routes objects and merges them into one Routes object.

type ServerOption

type ServerOption = func(*http.Server) error

ServerOption is a function which always for server configurations.

func WithAddr

func WithAddr(addr string) ServerOption

WithAddr configures the IP address and port to sserve requests.

func WithDefaultServerOptions

func WithDefaultServerOptions() []ServerOption

WithDefaultServerOptions provides an example method to use with the NewServer options using the default timeout values.

func WithInMemoryCookieStore

func WithInMemoryCookieStore(keyPairs ...[]byte) ServerOption

WithInMemoryCookieStore configures an in-memory cookie store.

func WithRoutes

func WithRoutes(r Routes, m ...RouteMiddleware) ServerOption

WithRoutes allows for custom routes to be added to a server.

Note: you can only use this method once within a NewServer method.

func WithServerDefaultTLSConfig

func WithServerDefaultTLSConfig() ServerOption

WithServerDefaultTLSConfig configures the server to use the DefaultServerTLSConfig.

func WithServerIdleTimeout

func WithServerIdleTimeout(d time.Duration) ServerOption

WithServerIdleTimeout can change the server's idle timeout.

func WithServerReadTimeout

func WithServerReadTimeout(d time.Duration) ServerOption

WithServerReadTimeout can change the server's read timeout.

func WithServerTLSConfig

func WithServerTLSConfig(c *tls.Config) ServerOption

WithServerTLSConfig can change the server's TLS configurations.

func WithServerWriteTimeout

func WithServerWriteTimeout(d time.Duration) ServerOption

WithServerWriteTimeout can change the server's write timeout.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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