Skip to content

Instantly share code, notes, and snippets.

@kazeburo
Created October 18, 2021 04:41
Show Gist options
  • Save kazeburo/8ea09fdbf250e1748600b107edd1366b to your computer and use it in GitHub Desktop.
Save kazeburo/8ea09fdbf250e1748600b107edd1366b to your computer and use it in GitHub Desktop.
fakeserver
package main
import (
"flag"
"fmt"
"log"
"net"
)
var header = []byte("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n")
var html = []byte(`<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
Reason: You're speaking plain HTTP to an SSL-enabled server port.<br />
Instead use the HTTPS scheme to access this URL, please.<br />
</p>
</body></html>
`)
func handleConnection(conn *net.TCPConn) {
defer conn.Close()
buf := make([]byte, 4*1024)
for {
n, err := conn.Read(buf)
if err != nil {
if ne, ok := err.(net.Error); ok {
switch {
case ne.Temporary():
continue
}
}
log.Println("Read", err)
return
}
if n > 0 {
break
}
}
log.Printf("%s %s", conn.RemoteAddr(), string(buf[0:7]))
//conn.Write(header)
_, err := conn.Write(html)
if err != nil {
log.Println("Write", err)
return
}
return
}
func handleListener(l *net.TCPListener) error {
defer l.Close()
for {
conn, err := l.AcceptTCP()
if err != nil {
if ne, ok := err.(net.Error); ok {
if ne.Temporary() {
log.Println("AcceptTCP", err)
continue
}
}
return err
}
go handleConnection(conn)
}
}
func main() {
port := flag.Uint("port", 12345, "port number to listen")
flag.Parse()
tcpAddr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("0.0.0.0:%d", *port))
if err != nil {
log.Println("ResolveTCPAddr", err)
return
}
l, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
log.Println("ListenTCP", err)
return
}
err = handleListener(l)
if err != nil {
log.Println("handleListener", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment