stock-ticker/handlers.go

79 lines
1.7 KiB
Go
Raw Permalink Normal View History

2023-02-19 16:28:25 +00:00
package main
import (
"encoding/json"
"fmt"
"sort"
"strings"
"net/http"
)
func healthCheckHandleFunc(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "I'm all good!")
}
func stockPriceHandleFunc(apiKey, symbol string, nWeeks int) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintf(w, "ERROR: The method '%s' is not allow at this endpoint.\n", r.Method)
return
}
resp, err := http.Get(fmt.Sprintf(requestURLFormat, symbol, apiKey))
if err != nil {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusBadGateway)
fmt.Fprintf(w, "ERROR: Unable to get a response from Alpha Vantage; %v\n", err)
return
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
var s Stock
if err := decoder.Decode(&s); err != nil {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusBadGateway)
fmt.Fprintf(w, "ERROR: Unable to decode the response from Alpha Vantage; %v\n", err)
return
}
if nWeeks > len(s.TimeSeries) {
nWeeks = len(s.TimeSeries)
}
var keys []string
for k := range s.TimeSeries {
keys = append(keys, k)
}
sort.Sort(sort.Reverse(sort.StringSlice(keys)))
var b strings.Builder
b.WriteString(fmt.Sprintf(tableFormat, s.MetaData.Symbol))
for i := 0; i < nWeeks; i++ {
b.WriteString(fmt.Sprintf("%s | %s\n", keys[i], s.TimeSeries[keys[i]].Close))
}
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, b.String())
}
}