/servers

HTTP, HTTPs, UNIX, gRPC servers with configs and context

Primary LanguageGoMIT LicenseMIT

servers

GoDev Build Status Coverage Status Go Report Card Deepsource.io Card

HTTP, HTTPs, gRPC, UNIX servers with configs and context

Quick-start

package main

import (
  "bytes"
  "context"
  "fmt"
  "http"
  "log"
  "sync"

  "google.golang.org/grpc"
  "github.com/go-x-pkg/servers"
)

func main() {
  var s servers.Servers

  config := `- kind: [unix, http]
  addr: /run/acme/acme.sock
- kind: inet
  host: 0.0.0.0
  port: 8000
- kind: [inet, grpc]
  host: 0.0.0.0
  port: 8443
  tls:
    enable: true
    cert-file: /etc/acme/tls.cert
    key-file: /etc/acme/tls.key
  grpc:
    # e.g. grpcurl
    reflection: true`

  if err := yaml.Unmarshal([]byte(config), &ss); err != nil {
    log.Fatalf("error unmarshal: %s", err)
  }

  listeners, err := ss.Listen()
  if len(errs) != 0 {
    listeners.Close()

    log.Fatalf("error listen: %#v", errs)
  }

  http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request) {
    log.Printf("[<] %#v %#v", w, r)
  })

  ctx := context.Background()
  ctx, cancel := context.WithCancel(ctx)
  defer cancel()

  wg := sync.WaitGroup()

  wg.Add(1)
  go func() {
    defer wg.Done()

    err := listeners.ServeHTTP(
      http.DefaultServerMux,

      servers.Context(ctx),
    )
  }()

  wg.Add(1)
  go func() {
    defer wg.Done()

    err := listeners.ServeGRPC(
      func (*grpc.Server) {
        # register gRPC servers here
      },

      servers.Context(ctx),
    )
  }()

  wg.Wait()
}

Config example

- kind: [unix, http]
  addr: /run/acme/acme.sock

- kind: inet
  host: 0.0.0.0
  port: 8000

- kind: [inet, grpc]
  host: 0.0.0.0
  port: 8443
  tls:
    enable: true
    cert-file: /etc/acme/tls.cert
    key-file: /etc/acme/tls.key
  grpc:
    # e.g. grpcurl
    reflection: true