Created
September 29, 2020 16:56
-
-
Save rikonor/0e4012ce18f9c8cdd94c6cbcf60f1606 to your computer and use it in GitHub Desktop.
Allow traffic from subnet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"net" | |
"net/http" | |
"strings" | |
) | |
func main() { | |
s := &http.Server{ | |
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprint(w, "OK") | |
}), | |
} | |
l, err := net.Listen("tcp4", ":8080") | |
if err != nil { | |
log.Fatal(err) | |
} | |
l = wrapWithAllowCIDR(l, "192.168.0.0/24") | |
if err := s.Serve(l); err != nil { | |
log.Fatal(err) | |
} | |
} | |
type StubListener struct { | |
AcceptFn func() (net.Conn, error) | |
CloseFn func() error | |
AddrFn func() net.Addr | |
} | |
var _ net.Listener = &StubListener{} | |
func (l *StubListener) Accept() (net.Conn, error) { | |
return l.AcceptFn() | |
} | |
func (l *StubListener) Close() error { | |
return l.CloseFn() | |
} | |
func (l *StubListener) Addr() net.Addr { | |
return l.AddrFn() | |
} | |
func wrapWithAllowCIDR(l net.Listener, cidr string) net.Listener { | |
_, ipn, err := net.ParseCIDR(cidr) | |
if err != nil { | |
panic(fmt.Sprintf("invalid cidr: %s", cidr)) | |
} | |
return &StubListener{ | |
AcceptFn: func() (net.Conn, error) { | |
c, err := l.Accept() | |
if err != nil { | |
return c, err | |
} | |
addrParts := strings.Split(c.RemoteAddr().String(), ":") | |
ip := net.ParseIP(addrParts[0]) | |
if !ipn.Contains(ip) { | |
return c, c.Close() | |
} | |
return c, nil | |
}, | |
CloseFn: l.Close, | |
AddrFn: l.Addr, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment