Last active
May 17, 2017 14:18
-
-
Save dthtvwls/59162132085197104e8649f293710d24 to your computer and use it in GitHub Desktop.
Ask if a word is in the dictionary via TCP
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 ( | |
"bufio" | |
"flag" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net" | |
"os" | |
"strconv" | |
"strings" | |
"unicode" | |
) | |
var dict = make(map[string]bool, 0) | |
func init() { | |
if file, err := os.Open("/usr/share/dict/words"); err != nil { | |
log.Fatalln(err) | |
} else { | |
defer file.Close() | |
scanner := bufio.NewScanner(file) | |
SCAN: | |
for scanner.Scan() { | |
word := scanner.Text() | |
if unicode.IsUpper(rune(word[0])) { | |
continue | |
} | |
for _, letter := range word { | |
if !unicode.IsLetter(letter) { | |
continue SCAN | |
} | |
} | |
dict[word] = true | |
} | |
} | |
flag.Parse() | |
} | |
func main() { | |
if ln, err := net.Listen("tcp", flag.Arg(0)); err != nil { | |
log.Fatalln(err) | |
} else { | |
defer ln.Close() | |
for { | |
if conn, err := ln.Accept(); err != nil { | |
log.Println(err) | |
} else { | |
go func() { | |
defer conn.Close() | |
if message, err := ioutil.ReadAll(bufio.NewReader(conn)); err != nil { | |
log.Println(err) | |
} else { | |
conn.Write([]byte(strconv.FormatBool(dict[strings.TrimSpace(string(message))]))) | |
} | |
}() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment