First try

This commit is contained in:
Dan Dobos
2021-11-01 09:14:39 +01:00
parent 7062f79255
commit 43380ec064
15 changed files with 1195 additions and 0 deletions
@@ -0,0 +1,70 @@
package pokemongotemplates
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func GetPokemons() (*[]Pokemon, error) {
//get pokemon data from api
resp, err := http.Get("https://pokeapi.co/api/v2/pokemon/?offset=0&limit=500")
if err != nil {
fmt.Println(err.Error())
}
defer resp.Body.Close()
// read api response
rowData, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err.Error())
}
var pokemonsData PokemonsAPIResponse
if err := json.Unmarshal(rowData, &pokemonsData); err != nil {
fmt.Println(err.Error())
}
PokemonSlice := make([]Pokemon, 0)
for i := range pokemonsData.Results {
resp, err := http.Get(pokemonsData.Results[i].URL)
if err != nil {
fmt.Println(err.Error())
}
defer resp.Body.Close()
rowData, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err.Error())
}
var pokemonDetails PokemonDetails
if err := json.Unmarshal(rowData, &pokemonDetails); err != nil {
fmt.Println(err.Error())
}
var pokeMoves string
for x := range pokemonDetails.Moves {
if x <= 3 {
pokeMoves += pokemonDetails.Moves[x].Move.Name + " "
}
}
var pokeTypes string
for z := range pokemonDetails.Types {
pokeTypes += pokemonDetails.Types[z].Type.Name + " "
}
PokemonSlice = append(PokemonSlice, Pokemon{
Name: pokemonDetails.Name,
Weight: pokemonDetails.Weight,
Height: pokemonDetails.Height,
Moves: pokeMoves,
Types: pokeTypes,
Image: pokemonDetails.Sprites.Other.OfficialArtwork.FrontDefault,
})
}
return &PokemonSlice, nil
}
@@ -0,0 +1,72 @@
package pokemongotemplates
type SiteLink struct {
Title string
Link string
}
var NavigationLinks = []SiteLink{
{
Title: "500 Pokemons",
Link: "/",
},
{
Title: "Choose how many",
Link: "/custom",
},
}
type Pokemon struct {
Name string
Weight int
Height int
Moves string
Types string
Image string
}
type PageData struct {
NavigationLinks []SiteLink
Data []Pokemon
}
type PokemonMove struct {
Name string `json:"name"`
}
type PokemonMoves struct {
Move PokemonMove `json:"move"`
}
type PokemonType struct {
Name string `json:"name"`
}
type PokemonTypes struct {
Type PokemonType `json:"type"`
}
type PokemonImage struct {
FrontDefault string `json:"front_default"`
}
type PokemonArtwork struct {
OfficialArtwork PokemonImage `json:"official-artwork"`
}
type PokemonSprites struct {
Other PokemonArtwork `json:"other"`
}
type PokemonDetails struct {
Name string `json:"name"`
Weight int `json:"weight"`
Height int `json:"height"`
Moves []PokemonMoves `json:"moves"`
Types []PokemonTypes `json:"types"`
Sprites PokemonSprites `json:"sprites"`
}
type PokemonAPIResult struct {
Name string `json:"name"`
URL string `json:"url"`
}
type PokemonsAPIResponse struct {
Results []PokemonAPIResult `json:"results"`
}
+37
View File
@@ -0,0 +1,37 @@
package infrastructure
import (
"log"
"github.com/spf13/viper"
)
type ApplicationEnvironment struct {
TemplateLocation string
}
func ConfigSetup(configName, configPath string) {
viper.SetConfigName(configName)
viper.SetConfigType("toml")
viper.AddConfigPath(configPath)
}
func ValidateVariablesAreSet(variables []string) {
for i := range variables {
if !viper.IsSet(variables[i]) {
log.Fatalf("%s variable was not set!\nAborting application start!", variables[i])
}
}
}
func GetConfig() ApplicationEnvironment {
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("fatal error config file in infrastructure: %s", err)
}
ValidateVariablesAreSet([]string{})
return ApplicationEnvironment{
TemplateLocation: viper.GetString("TemplateLocation"),
}
}
+80
View File
@@ -0,0 +1,80 @@
package app
import (
"fmt"
"io/fs"
"net/http"
"path/filepath"
"strings"
"time"
"github.com/diaid83/pokemongotemplates/internal/infrastructure"
"github.com/gin-gonic/gin"
)
type ApplicationState struct {
HTTPServer *http.Server
Handler *gin.Engine
Config *infrastructure.ApplicationEnvironment
}
type ApplicationServer struct {
State ApplicationState
}
func (s *ApplicationServer) registerHandlers() {
var files []string
templateLocation := fmt.Sprintf("%s/web/templates", s.State.Config.TemplateLocation)
err := filepath.Walk(templateLocation, func(path string, info fs.FileInfo, err error) error {
if strings.HasSuffix(path, ".gohtml") {
files = append(files, path)
}
return nil
})
if err != nil {
panic(err.Error())
}
s.State.Handler.LoadHTMLFiles(files...)
s.State.Handler.GET("/", s.pokemonPageHandler())
s.State.Handler.GET("/custom", s.customPokemonPageHandler())
}
func NewApplicationServer(userOptions *ApplicationState) *ApplicationServer {
state := userOptions
if state == nil {
state = &ApplicationState{}
}
if state.Handler == nil {
gin.SetMode(gin.ReleaseMode)
state.Handler = gin.Default()
}
if state.HTTPServer == nil {
state.HTTPServer = &http.Server{
ReadTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 100 * time.Second,
Addr: ":8080",
Handler: state.Handler,
}
}
if state.Config == nil {
config := infrastructure.GetConfig()
state.Config = &config
}
s := ApplicationServer{
State: ApplicationState{
HTTPServer: state.HTTPServer,
Handler: state.Handler,
Config: state.Config,
},
}
s.registerHandlers()
return &s
}
@@ -0,0 +1,29 @@
package app
import (
"fmt"
"net/http"
"github.com/diaid83/pokemongotemplates/internal/domain/pokemongotemplates"
"github.com/gin-gonic/gin"
)
func (s *ApplicationServer) pokemonPageHandler() func(*gin.Context) {
data, err := pokemongotemplates.GetPokemons()
if err != nil {
fmt.Println(err.Error())
}
return func(c *gin.Context) {
c.HTML(http.StatusOK, "views/Pokemons.gohtml", pokemongotemplates.PageData{
NavigationLinks: pokemongotemplates.NavigationLinks,
Data: *data,
})
}
}
func (s *ApplicationServer) customPokemonPageHandler() func(*gin.Context) {
return func(c *gin.Context) {
c.HTML(http.StatusOK, "views/CustomPokemons.gohtml", pokemongotemplates.PageData{
NavigationLinks: pokemongotemplates.NavigationLinks,
})
}
}