Created
October 26, 2017 18:33
-
-
Save CyrusRoshan/9c9efd43f6ef86d10446cb6a25f6dc7d to your computer and use it in GitHub Desktop.
Simple request reader and poster, with IP Banning, for workshop #1
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" | |
"io" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"regexp" | |
) | |
const IPBANS = true | |
var ipBanWords = regexp.MustCompile("fuck|shit|bitch") | |
var bannedIPs = make(map[string]bool) | |
func main() { | |
trickMux := http.NewServeMux() | |
trickMux.HandleFunc("/", defaultHandler) | |
go http.ListenAndServe(":80", trickMux) | |
realMux := http.NewServeMux() | |
realMux.HandleFunc("/", handler) | |
http.ListenAndServe(":8000", realMux) | |
} | |
func defaultHandler(w http.ResponseWriter, r *http.Request) { | |
io.WriteString(w, "Hey friend! You've actually gotta hit port 8000 to post a message.") | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
ipaddr := r.RemoteAddr | |
// Handle BANS | |
fmt.Println(bannedIPs) | |
if IPBANS { | |
if bannedIPs[ipaddr] { | |
log.Println("user", ipaddr, "tried to request, after being banned") | |
io.WriteString(w, "Hey buckaroo, you're BANNED! Let's not sabotage this workshop.") | |
return | |
} | |
} | |
// Handle wrong REST method | |
if r.Method != "POST" { | |
io.WriteString(w, "Hey, you've got to send a POST request using curl, to send data.") | |
return | |
} | |
// Handle message reading | |
messageByte, err := ioutil.ReadAll(r.Body) | |
if err != nil { | |
fmt.Println(err) | |
io.WriteString(w, "wow I think you messed something up") | |
return | |
} | |
message := string(messageByte) | |
// Handle empty messages | |
if message == "" { | |
io.WriteString(w, "Hey, you didn't post anything, friend! Try looking into the -d flag in curl.") | |
return | |
} | |
// Handle bad words | |
if ipBanWords.MatchString(message) { | |
if IPBANS { | |
bannedIPs[ipaddr] = true | |
log.Println("user", ipaddr, "is an edgy teen and has been IPBANNED") | |
io.WriteString(w, "Not very nice, friendo, you're banned!") | |
return | |
} | |
log.Println("user", ipaddr, "is an edgy teen") | |
io.WriteString(w, "Not very nice, friendo") | |
return | |
} | |
// Actually post a message | |
log.Printf("user %s wrote `%s`", ipaddr, message) | |
// Server response | |
io.WriteString(w, "Nice! You successfully posted!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment