Last active
March 30, 2020 22:10
-
-
Save lornasong/797debe8be4e9f450203f3cf9f185386 to your computer and use it in GitHub Desktop.
GHC 2020 - Golang Workshop
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
// Grace Hopper Convention 2020 - Microservice example for beginner Go workshop | |
// Contains a basic microservice using Go standard library, suggestions for | |
// features to work on and bug(s) for participants to find. | |
package main | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
"strings" | |
) | |
// Start running the microservice with our endpoints | |
func main() { | |
stats := make(map[string]int) | |
// ** Potential Feature: const statsAPIBase = "/stats/" e.g. /stats/angry | |
http.Handle("/emoji/", &EmojiHandler{stats}) | |
http.Handle("/count", &CountEmojiHandler{stats}) | |
port := ":8080" | |
fmt.Println("Serving on port", port) | |
log.Fatal(http.ListenAndServe(port, nil)) | |
} | |
// EmojiHandler handles emoji API requests. Given an string for an emoji, returns the | |
// emoji icon. It is an implementation of the `net/http` standard library interface | |
// Handler which must implement `ServeHTTP` | |
type EmojiHandler struct { | |
stats map[string]int | |
} | |
// ServeHTTP serves the emoji endpoint | |
// ** Potential Feature: support more emojis e.g. /emoji/sad, /emoji/smile | |
func (e *EmojiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
log.Println("Request:", r.URL.Path) | |
param := strings.TrimPrefix(r.URL.Path, "/emoji/") | |
if param == "angry" { | |
angryCount := e.stats["angry"] | |
angryCount++ | |
fmt.Fprintln(w, "😠") | |
return | |
} | |
http.Error(w, http.StatusText(http.StatusNotImplemented), http.StatusNotImplemented) | |
} | |
// CountEmojiHandler handles counts succesful emoji API requests. Returns the number of requests that have | |
// been made to the emoji API | |
type CountEmojiHandler struct { | |
stats map[string]int | |
} | |
// ServeHTTP serves the count endpoint | |
func (c *CountEmojiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
log.Println("Request:", r.URL.Path) | |
count := 0 | |
for key, value := range c.stats { | |
count := count + value | |
log.Println("key:", key, " value:", value, " count:", count) | |
} | |
fmt.Fprintln(w, count) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment