Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version: 1.23
go-version: 1.24

- name: Build
run: go build -v ./...
Expand Down
6 changes: 3 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
FROM golang:1.22-alpine as builder
FROM golang:1.24-alpine as builder

RUN apk -U --no-cache add curl ca-certificates python3

WORKDIR /app

COPY . /app/

RUN go test ./... && go build .
RUN go build . && go test -v ./...

FROM alpine:3.19 as final
FROM alpine:3.22 as final

COPY --from=builder /app/microproxy /usr/local/bin/

Expand Down
2 changes: 2 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (

type Configuration struct {
Listen string `toml:"listen"`
HTTPListen string `toml:"http_listen"`
HealthCheckEnabled string `toml:"enable_health_check"`
AccessLog string `toml:"access_log"`
ActivityLog string `toml:"activity_log"`
AllowedConnectPorts []int `toml:"allowed_connect_ports"`
Expand Down
10 changes: 10 additions & 0 deletions config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ func compareSlices(s1, s2 []int) bool {
func TestConfigFile(t *testing.T) {
expected := Configuration{
Listen: "127.0.0.1:3129",
HTTPListen: "127.0.0.1:8080",
HealthCheckEnabled: "on",
AccessLog: "/tmp/microproxy.access.log",
AuthType: "basic",
AuthRealm: "proxy",
Expand Down Expand Up @@ -59,4 +61,12 @@ func TestConfigFile(t *testing.T) {
if conf.ForwardedForHeader != expected.ForwardedForHeader {
t.Errorf("Got %v, expected %v", conf.ForwardedForHeader, expected.ForwardedForHeader)
}

if conf.HTTPListen != expected.HTTPListen {
t.Errorf("Got %v, expected %v", conf.HTTPListen, expected.HTTPListen)
}

if conf.HealthCheckEnabled != expected.HealthCheckEnabled {
t.Errorf("Got %v, expected %v", conf.HealthCheckEnabled, expected.HealthCheckEnabled)
}
}
3 changes: 3 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,8 @@ services:
context: .
dockerfile: Dockerfile
image: microproxy:latest
command: [ "microproxy", "-config", "/usr/local/etc/microproxy.toml", "-i" ]
ports:
- "3128:3128"
volumes:
- ./microproxy-docker.toml:/usr/local/etc/microproxy.toml
8 changes: 4 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
module github.com/thekvs/microproxy

go 1.23.0
go 1.24.0

require (
github.com/BurntSushi/toml v1.5.0
github.com/BurntSushi/toml v1.6.0
github.com/elazarl/goproxy v1.7.2
)

require (
golang.org/x/net v0.38.0 // indirect
golang.org/x/text v0.23.0 // indirect
golang.org/x/net v0.48.0 // indirect
golang.org/x/text v0.32.0 // indirect
)
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/elazarl/goproxy v1.7.2 h1:Y2o6urb7Eule09PjlhQRGNsqRfPmYI3KKQLFpCAV3+o=
Expand All @@ -10,7 +12,11 @@ github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOf
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
70 changes: 64 additions & 6 deletions microproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ func setActivityLog(conf *Configuration, proxy *goproxy.ProxyHttpServer) {
}
}

func setSignalHandler(conf *Configuration, proxy *goproxy.ProxyHttpServer, logger *ProxyLogger) {
func setSignalHandler(conf *Configuration, proxy *goproxy.ProxyHttpServer, logger *ProxyLogger, cancel context.CancelFunc) {
signalChannel := make(chan os.Signal, 1)
signal.Notify(signalChannel, os.Interrupt, syscall.SIGTERM, syscall.SIGUSR1)

Expand All @@ -357,6 +357,7 @@ func setSignalHandler(conf *Configuration, proxy *goproxy.ProxyHttpServer, logge
if err != nil {
log.Printf("Close error: %v", err)
}
cancel()
os.Exit(0)
case syscall.SIGUSR1:
proxy.Logger.Printf("got USR1 signal, reopening logs\n")
Expand Down Expand Up @@ -528,14 +529,55 @@ func setForwardProxy(conf *Configuration, proxy *goproxy.ProxyHttpServer) {
}
}

func startServer(addr string, handler http.Handler) error {
func startProxyServer(addr string, handler http.Handler) error {
err := http.ListenAndServe(addr, handler)
if err != nil {
return fmt.Errorf("failed to start server: %w", err)
}
return nil
}

func startHTTPServer(addr string, health *ProxyHealth) error {
mux := http.NewServeMux()
mux.HandleFunc("/health", healthCheckHandler(health)) // Health check endpoint

server := &http.Server{
Addr: addr,
Handler: mux,
}

err := server.ListenAndServe()
if err != nil {
return fmt.Errorf("failed to start server: %w", err)
}
return nil
}

func healthCheckHandler(health *ProxyHealth) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if health.IsHealthy() {
fmt.Fprintln(w, "Proxy is healthy")
} else {
http.Error(w, "Proxy is unhealthy", http.StatusServiceUnavailable)
}
}
}

func setupProxyHealthHandlers(conf *Configuration, proxy *goproxy.ProxyHttpServer, health *ProxyHealth) {
if conf.HealthCheckEnabled == "on" {
proxy.OnResponse().DoFunc(
func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
proxy.Logger.Printf("Response code: %s", resp.StatusCode)
if resp.StatusCode == http.StatusProxyAuthRequired {
health.RecordFailure() // record a failure for auth errors
} else {
health.RecordSuccess() // record a success for valid responses
}
return resp
})
}
}

func main() {
configFile := flag.String("config", "microproxy.toml", "proxy configuration file")
proxyInsecure := flag.Bool("i", false, "allow insecure forward proxy connections")
Expand All @@ -551,19 +593,26 @@ func main() {
os.Exit(0)
}

// Create a context to handle termination signals
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

proxy := createProxy(conf)
proxy.Verbose = *verboseMode

logger := newProxyLogger(conf)

health := &ProxyHealth{Healthy: true, FailureLimit: 5}

setHTTPLoggingHandler(proxy, logger)
setForwardProxy(conf, proxy)
setAllowedConnectPortsHandler(conf, proxy)
setAllowedNetworksHandler(conf, proxy)
setForwardedForHeaderHandler(conf, proxy)
setViaHeaderHandler(conf, proxy)
setAddCustomHeadersHandler(conf, proxy)
setSignalHandler(conf, proxy, logger)
setupProxyHealthHandlers(conf, proxy, health)
setSignalHandler(conf, proxy, logger, cancel)

// To be called first while processing handlers' stack,
// has to be placed last in the source code.
Expand All @@ -574,8 +623,17 @@ func main() {
}

proxy.Logger.Printf("starting proxy\n")
proxy.Logger.Printf("listening on %v\n", conf.Listen)
proxy.Logger.Printf("using configuration file %v\n", *configFile)

log.Fatal(startServer(conf.Listen, proxy))
go func() {
log.Fatal(startProxyServer(conf.Listen, proxy))
}()

if conf.HealthCheckEnabled == "on" {
go func() {
log.Fatal(startHTTPServer(conf.HTTPListen, health))
}()
}

// Wait for the context to be closed
<-ctx.Done()
}
2 changes: 2 additions & 0 deletions microproxy.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
listen="127.0.0.1:3129"
enable_health_check="on"
http_listen="127.0.0.1:8080"
access_log="/tmp/microproxy.access.log"
activity_log="/tmp/microproxy.error.log"
allowed_connect_ports=[443, 80]
Expand Down
32 changes: 32 additions & 0 deletions proxyhealth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package main

import "sync"

type ProxyHealth struct {
sync.Mutex
Healthy bool
FailureCount int
FailureLimit int // Threshold of failures to consider the proxy as unhealthy
}

func (p *ProxyHealth) RecordFailure() {
p.Lock()
defer p.Unlock()
p.FailureCount++
if p.FailureCount >= p.FailureLimit {
p.Healthy = false
}
}

func (p *ProxyHealth) RecordSuccess() {
p.Lock()
defer p.Unlock()
p.Healthy = true
p.FailureCount = 0 // reset failure count on a successful request
}

func (p *ProxyHealth) IsHealthy() bool {
p.Lock()
defer p.Unlock()
return p.Healthy
}
2 changes: 1 addition & 1 deletion vendor/github.com/BurntSushi/toml/README.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 8 additions & 1 deletion vendor/github.com/BurntSushi/toml/decode.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading