feat(go): add go as a template
add go as a template when i need to
This commit is contained in:
parent
edcf6f758e
commit
cd612f03ad
8 changed files with 224 additions and 1 deletions
108
templates/go/main.go
Normal file
108
templates/go/main.go
Normal file
|
@ -0,0 +1,108 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Quote struct {
|
||||
Quote string `json:"quote"`
|
||||
Author string `json:"author"`
|
||||
}
|
||||
|
||||
func (q Quote) PrintQuote() {
|
||||
fmt.Printf("\"%s\" - %s\n", q.Quote, q.Author)
|
||||
}
|
||||
|
||||
func GetResponse() (*http.Response, error) {
|
||||
var url string = "https://dummyjson.com/quotes/random"
|
||||
var res *http.Response
|
||||
var err error
|
||||
var attempts int = 4
|
||||
|
||||
for attempts != 0 {
|
||||
res, err = http.Get(url)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "Error encountered... trying again...")
|
||||
time.Sleep(2 * time.Second)
|
||||
attempts--
|
||||
continue
|
||||
}
|
||||
|
||||
if res.StatusCode != 200 {
|
||||
fmt.Fprintf(os.Stderr, "API returned but a 200, so I will be running this again in a few seconds.")
|
||||
time.Sleep(2 * time.Second)
|
||||
attempts--
|
||||
continue
|
||||
}
|
||||
|
||||
if res.StatusCode == 200 {
|
||||
return res, nil
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if res.StatusCode != 200 {
|
||||
return nil, errors.New("Gave up attempting to get 200.")
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func GetBodyFromResponse(res *http.Response) ([]byte, error) {
|
||||
var body []byte
|
||||
var err error
|
||||
|
||||
defer res.Body.Close()
|
||||
body, err = io.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func NewQuoteFromBody(body []byte) (Quote, error) {
|
||||
var quote Quote
|
||||
var err error
|
||||
|
||||
err = json.Unmarshal(body, "e)
|
||||
if err != nil {
|
||||
return Quote{}, err
|
||||
}
|
||||
|
||||
return quote, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
var err error
|
||||
var res *http.Response
|
||||
|
||||
res, err = GetResponse()
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
|
||||
var body []byte
|
||||
body, err = GetBodyFromResponse(res)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
|
||||
var quote Quote
|
||||
quote, err = NewQuoteFromBody(body)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
|
||||
quote.PrintQuote()
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue