aboutsummaryrefslogtreecommitdiff
path: root/transport/http.go
blob: 663bb31ec2bc1f896b88ec8e5a508e01f992f96f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package transport

import (
	"context"
	"crypto/tls"
	"net"
	"net/http"
)

type HTTP struct {
	Bind string
	TLS  *tls.Config
}

func (h *HTTP) Run(ctx context.Context, resolver Resolver) error {
	srv := http.Server{
		Addr: h.Bind,
		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.Method != http.MethodPost {
				w.WriteHeader(http.StatusMethodNotAllowed)
				return
			}
			w.WriteHeader(http.StatusOK)
			w.Header().Set("Content-Type", "application/json")
			resolver.Resolve(ctx, r.Body, w)
		}),
		BaseContext: func(l net.Listener) context.Context {
			return ctx
		},
		TLSConfig: h.TLS,
	}
	go func() {
		<-ctx.Done()
		srv.Close()
	}()
	if err := srv.ListenAndServe(); err != http.ErrServerClosed {
		return err
	}
	return nil
}