69 lines
1.5 KiB
Go
Executable File
69 lines
1.5 KiB
Go
Executable File
package server
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"local/rproxy3/config"
|
|
"local/rproxy3/storage"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"golang.org/x/time/rate"
|
|
)
|
|
|
|
func TestServerStart(t *testing.T) {
|
|
server := mockServer()
|
|
|
|
p := config.Proxy{
|
|
To: "http://hello.localhost" + server.addr,
|
|
}
|
|
if err := server.Route("world", p); err != nil {
|
|
t.Fatalf("cannot add route: %v", err)
|
|
}
|
|
|
|
go func() {
|
|
if err := server.Run(); err != nil {
|
|
t.Fatalf("err running server: %v", err)
|
|
}
|
|
}()
|
|
|
|
r, _ := http.NewRequest("GET", "http://world.localhost"+server.addr, nil)
|
|
if _, err := (&http.Client{}).Do(r); err != nil {
|
|
t.Errorf("failed to get: %v", err)
|
|
}
|
|
}
|
|
|
|
func mockServer() *Server {
|
|
portServer := httptest.NewServer(nil)
|
|
port := strings.Split(portServer.URL, ":")[2]
|
|
portServer.Close()
|
|
s := &Server{
|
|
db: storage.NewMap(),
|
|
addr: ":" + port,
|
|
limiter: rate.NewLimiter(rate.Limit(50), 50),
|
|
}
|
|
if err := s.Routes(); err != nil {
|
|
panic(fmt.Sprintf("cannot initiate server routes; %v", err))
|
|
}
|
|
return s
|
|
}
|
|
|
|
func TestServerRoute(t *testing.T) {
|
|
server := mockServer()
|
|
p := config.Proxy{
|
|
To: "http://hello.localhost" + server.addr,
|
|
}
|
|
if err := server.Route("world", p); err != nil {
|
|
t.Fatalf("cannot add route: %v", err)
|
|
}
|
|
w := httptest.NewRecorder()
|
|
r, _ := http.NewRequest("GET", "http://world.localhost"+server.addr, nil)
|
|
r = r.WithContext(context.Background())
|
|
server.ServeHTTP(w, r)
|
|
if w.Code != 502 {
|
|
t.Fatalf("cannot proxy from 'world' to 'hello', status %v", w.Code)
|
|
}
|
|
}
|