server test
parent
55c540e9c2
commit
6f8e2e5c53
|
|
@ -0,0 +1,21 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if err := h.serveHTTP(w, r); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func (h Handler) serveHTTP(w http.ResponseWriter, r *http.Request) error {
|
||||
return io.EOF
|
||||
}
|
||||
|
|
@ -2,9 +2,46 @@ package server
|
|||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func Main(ctx context.Context) error {
|
||||
return io.EOF
|
||||
port, _ := strconv.Atoi(os.Getenv("PORT"))
|
||||
if port == 0 {
|
||||
port = 10000
|
||||
}
|
||||
|
||||
return Run(ctx, fmt.Sprintf(":%d", port))
|
||||
}
|
||||
|
||||
func Run(ctx context.Context, listen string) error {
|
||||
ctx, can := context.WithCancel(ctx)
|
||||
defer can()
|
||||
|
||||
s := http.Server{
|
||||
Addr: listen,
|
||||
Handler: Handler{ctx: ctx},
|
||||
BaseContext: func(net.Listener) context.Context { return ctx },
|
||||
}
|
||||
defer s.Close()
|
||||
|
||||
errs := make(chan error)
|
||||
go func() {
|
||||
defer close(errs)
|
||||
select {
|
||||
case errs <- s.ListenAndServe():
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case err := <-errs:
|
||||
return err
|
||||
}
|
||||
return s.Close()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,50 @@
|
|||
package server_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"show-rss/src/cmd/server"
|
||||
"show-rss/src/db"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestServerStarts(t *testing.T) {
|
||||
With(t, func(url string) {
|
||||
})
|
||||
}
|
||||
|
||||
func With(t *testing.T, cb func(url string)) {
|
||||
ctx, can := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer can()
|
||||
|
||||
listen := func() string {
|
||||
s := httptest.NewServer(http.HandlerFunc(http.NotFound))
|
||||
s.Close()
|
||||
u, _ := url.Parse(s.URL)
|
||||
return u.Host
|
||||
}()
|
||||
|
||||
go func() {
|
||||
if err := server.Run(db.Test(t, ctx), listen); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}()
|
||||
|
||||
url := "http://" + listen
|
||||
for {
|
||||
if resp, err := http.Get(url); err == nil {
|
||||
resp.Body.Close()
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
case <-ctx.Done():
|
||||
t.Fatal(ctx.Err())
|
||||
}
|
||||
}
|
||||
|
||||
cb(url)
|
||||
}
|
||||
Loading…
Reference in New Issue