79 lines
1.7 KiB
Go
79 lines
1.7 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"runtime"
|
|
"strconv"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type listener struct {
|
|
net.Listener
|
|
slots chan struct{}
|
|
}
|
|
|
|
type connection struct {
|
|
net.Conn
|
|
slots chan struct{}
|
|
once sync.Once
|
|
}
|
|
|
|
func (value *connection) Close() error {
|
|
err := value.Conn.Close()
|
|
value.once.Do(func() { <-value.slots })
|
|
return err
|
|
}
|
|
|
|
func (value *listener) Accept() (net.Conn, error) {
|
|
value.slots <- struct{}{}
|
|
stream, err := value.Listener.Accept()
|
|
if err != nil {
|
|
<-value.slots
|
|
return nil, err
|
|
}
|
|
return &connection{Conn: stream, slots: value.slots}, nil
|
|
}
|
|
|
|
func main() {
|
|
capacity, err := strconv.Atoi(os.Args[1])
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
runtime.GOMAXPROCS(2)
|
|
bound, err := net.Listen("tcp", "127.0.0.1:0")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
server := http.Server{
|
|
ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second,
|
|
IdleTimeout: 5 * time.Second, MaxHeaderBytes: 8192,
|
|
Handler: http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
|
defer request.Body.Close()
|
|
body, err := io.ReadAll(http.MaxBytesReader(writer, request.Body, 65536))
|
|
if err != nil {
|
|
http.Error(writer, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
switch request.URL.RequestURI() {
|
|
case "/json":
|
|
writer.Header().Set("Content-Type", "application/json")
|
|
writer.Write([]byte(`{"ok":true}`))
|
|
case "/echo":
|
|
writer.Header().Set("Content-Type", "application/octet-stream")
|
|
writer.Write(body)
|
|
default:
|
|
writer.WriteHeader(http.StatusNotFound)
|
|
}
|
|
}),
|
|
}
|
|
fmt.Printf("READY|%d\n", bound.Addr().(*net.TCPAddr).Port)
|
|
if err := server.Serve(&listener{Listener: bound, slots: make(chan struct{}, capacity)}); err != nil {
|
|
panic(err)
|
|
}
|
|
}
|