Skip to content

Instantly share code, notes, and snippets.

@CyrusRoshan
Created October 27, 2017 02:58
Show Gist options
  • Save CyrusRoshan/0c86a811b865da535c103cd0967e4320 to your computer and use it in GitHub Desktop.
Save CyrusRoshan/0c86a811b865da535c103cd0967e4320 to your computer and use it in GitHub Desktop.
[UNFINISHED] Chat server for backend workshop
package main
import (
"net/http"
"strings"
)
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8000", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
path := strings.Split(r.URL.Path, "/")
if len(path) < 3 {
w.WriteHeader(500)
return
}
username1 := path[1]
username2 := path[2]
if r.Method == "POST" {
// handle sending messages
return
}
if r.Method == "GET" {
// handle reading messages
messages := getMessages(username1, username2)
splitMessageString := "messages:\n" + strings.Join(messages, "\n")
w.WriteHeader(200)
w.Write([]byte(splitMessageString))
return
}
w.Write([]byte("Route not found"))
w.WriteHeader(404)
return
}
// user1 -> user2 -> shared map between user 1, user 2
type user struct {
name string // name of the object
conversations map[string]*[]string
}
var users = make(map[string]*user)
func createUser(username string) *user {
conversations := make(map[string]*[]string)
newUser := user{
name: username,
conversations: conversations,
}
users[username] = &newUser
return &newUser
}
func sendMessage(username1 string, username2 string, message string) {
user1, exists := users[username1]
if !exists {
user1 = createUser(username1)
}
user2, exists := users[username2]
if !exists {
user2 = createUser(username2)
}
userAndMessage := username1 + ": " + message
messages := user1.conversations[username2]
if messages == nil {
messages = &[]string{userAndMessage}
user1.conversations[username2] = messages
user2.conversations[username1] = messages
} else {
*messages = append(*messages, userAndMessage)
}
}
func getMessages(username1 string, username2 string) []string {
if (users[username1] == nil) {
return []string{}
}
messages := users[username1].conversations[username2]
return *messages
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment