Skip to content

Instantly share code, notes, and snippets.

@adhadse
Created October 12, 2022 05:17
Show Gist options
  • Save adhadse/9eac30893634945aeba0aca3c754a4c5 to your computer and use it in GitHub Desktop.
Save adhadse/9eac30893634945aeba0aca3c754a4c5 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"regexp"
)
type User struct {
Id string `json:"Id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
DOB string `json:"date_of_birth"`
Email string `json:"email"`
PhoneNumber string `json:"phone_number"`
}
type Response struct {
Status int `json:"status"`
Response any `json:"response"`
}
// Index let's declare a global Index array
// that we can then populate in our main function
// to simulate a database
var Index = make(map[string]User)
var (
getUserRe = regexp.MustCompile(`^\/users\/(\d+)$`)
createUserRe = regexp.MustCompile(`^\/users[\/]*$`)
)
func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Println("Endpoint Hit: homePage")
response := Response{Status: http.StatusOK, Response: "Welcome to the Simple API!"}
json.NewEncoder(w).Encode(response)
}
func userHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Endpoint Hit: returnUser")
switch {
case r.Method == http.MethodGet && getUserRe.MatchString(r.URL.Path):
if len(Index) == 0 {
// if Index is empty, i.e,. no users
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(Response{Status: http.StatusNotFound, Response: "Empty database"})
} else {
matches := getUserRe.FindStringSubmatch(r.URL.Path)
user, ok := Index[matches[1]] // check if Index has user.
if len(matches) < 2 {
// if url in not in the format `/users/1`
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(Response{Status: http.StatusNotFound, Response: "User not found."})
} else if ok {
// if Index has the user
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(Response{Status: http.StatusOK, Response: user})
} else {
// if Index don't have any user
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(Response{Status: http.StatusNotFound, Response: "User not found."})
}
}
case r.Method == http.MethodPost && createUserRe.MatchString(r.URL.Path):
// case to handle adding a User; IDK if it works
var u User
if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(Response{Status: http.StatusInternalServerError, Response: "Internal Server Error."})
return
}
Index[u.Id] = u
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(Response{Status: http.StatusCreated, Response: "User added"})
}
}
func returnAllUsers(w http.ResponseWriter, r *http.Request) {
fmt.Println("Endpoint Hit: returnAllUsers")
json.NewEncoder(w).Encode(Index)
}
func handleRequests() {
http.HandleFunc("/", homePage)
http.HandleFunc("/users", returnAllUsers)
http.HandleFunc("/users/", userHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func main() {
handleRequests()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment