go-srvc / mods / httpmod

github.com/go-srvc/mods/httpmod

pkg.go.dev source
go get github.com/go-srvc/mods/httpmod@v0.1.4

README

httpmod

package main

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

	"github.com/go-srvc/mods/httpmod"
	"github.com/go-srvc/srvc"
)

func main() {
	srvc.RunAndExit(
		httpmod.New(
			httpmod.WithServerFn(CreateServer),
		),
	)
}

func CreateServer() (*http.Server, error) {
	addr := os.Getenv("ADDR")
	if addr == "" {
		return nil, errors.New("ADDR is required")
	}

	mux := http.NewServeMux()
	mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "World!")
	})

	return &http.Server{
		Addr:    addr,
		Handler: mux,
	}, nil
}

Overview

Package httpmod provides http server as module.

Constants

const ID = "httpmod"

Types

type Opt

type Opt func(s *Server) error

type Server

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

func (*Server) ID

func (s *Server) ID() string

func (*Server) Init

func (s *Server) Init() error

Init starts net.Listener after applying all options. Options are applied in same order as they were provided.

func (*Server) Run

func (s *Server) Run() error

Run starts serving http request and can be called after initialization.

func (*Server) Stop

func (s *Server) Stop() error

Stop calls shutdown for server.

func (*Server) URL

func (s *Server) URL() string

URL returns server's URL and can be called after initialization.

Examples

ExampleNew

package main

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

	"github.com/go-srvc/mods/httpmod"
	"github.com/go-srvc/srvc"
)

func main() {
	srvc.RunAndExit(
		httpmod.New(
			httpmod.WithServer(&http.Server{ReadHeaderTimeout: time.Second}),
			httpmod.WithAddr("127.0.0.1:0"),
			httpmod.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				fmt.Fprint(w, "Hello")
			})),
		),
	)
}