DEV Community

Kaike Castro
Kaike Castro

Posted on

4

Construindo uma Pokédex Simples com Golang e a Poke API

Você já quis criar sua própria Pokédex digital para explorar os Pokémon? Neste tutorial, vamos explorar como criar uma Pokédex simples usando a linguagem de programação Golang e a Poke API. Vamos criar uma interface web onde você pode pesquisar e visualizar informações sobre seus Pokémon favoritos.

Pré-requisitos

Antes de começarmos, você precisará ter o Golang instalado em seu sistema. Certifique-se de que sua máquina atenda a esses requisitos e que você tenha um ambiente de desenvolvimento Golang configurado.

Configurando o ambiente

Primeiro, vamos criar uma nova pasta para nosso projeto e inicializar um módulo Go:

mkdir pokedex-golang
cd pokedex-golang
go mod init pokedex
Enter fullscreen mode Exit fullscreen mode

Agora, vamos instalar algumas bibliotecas que iremos utilizar:

go get github.com/gorilla/mux
go get github.com/gorilla/handlers
Enter fullscreen mode Exit fullscreen mode

Criando a estrutura do projeto

Crie os seguintes diretórios para organizar nosso projeto:

mkdir templates
Enter fullscreen mode Exit fullscreen mode

Escrevendo o código

Aqui está o código para nossa aplicação em Golang:

// main.go
package main

import (
 "html/template"
 "net/http"
 "log"
 "github.com/gorilla/mux"
 "github.com/gorilla/handlers"
)

var tpl = template.Must(template.ParseFiles("templates/index.html"))

func IndexHandler(w http.ResponseWriter, r *http.Request) {
 tpl.Execute(w, nil)
}

func main() {
 r := mux.NewRouter()
 r.HandleFunc("/", IndexHandler)

 http.Handle("/", r)

 allowedOrigins := handlers.AllowedOrigins([]string{"*"})
 allowedMethods := handlers.AllowedMethods([]string{"GET", "POST", "OPTIONS"})

 log.Println("Server started on :8080...")
 http.ListenAndServe(":8080", handlers.CORS(allowedOrigins, allowedMethods)(r))
}
Enter fullscreen mode Exit fullscreen mode

Aqui, estamos criando um servidor web simples usando o pacote gorilla/mux para roteamento e gorilla/handlers para permitir solicitações de diferentes origens.

Criando o template HTML

Agora, crie o arquivo index.html dentro da pasta templates:

<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
 <title>Pokédex</title>
</head>
<body>
 <h1>Pokédex</h1>
 <input type="text" id="pokemonName" placeholder="Digite o nome do Pokémon">
 <button onclick="searchPokemon()">Pesquisar</button>
 <div id="pokemonInfo"></div>

 <script>
  function searchPokemon() {
   const name = document.getElementById("pokemonName").value;
   fetch(`https://pokeapi.co/api/v2/pokemon/${name.toLowerCase()}`)
    .then(response => response.json())
    .then(data => {
     const pokemonInfo = document.getElementById("pokemonInfo");
     pokemonInfo.innerHTML = `
      <h2>${data.name}</h2>
      <img src="${data.sprites.front_default}" alt="${data.name}">
      <p>Tipo: ${data.types.map(type => type.type.name).join(', ')}</p>
      <p>Peso: ${data.weight} kg</p>
      <p>Altura: ${data.height} </p>
     `;
    })
    .catch(error => {
     console.error(error);
     alert("Pokémon não encontrado!");
    });
  }
 </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Este é o template HTML que cria a interface da Pokédex. Ele inclui um campo de pesquisa onde você pode digitar o nome do Pokémon e exibe as informações do Pokémon pesquisado.

Executando o aplicativo

Para iniciar o aplicativo, execute o seguinte comando na raiz do seu projeto:

go run main.go
Enter fullscreen mode Exit fullscreen mode

Agora você pode acessar a Pokédex em seu navegador em http://localhost:8080 e começar a pesquisar seus Pokémon favoritos!

Conclusão

Neste tutorial, construímos uma Pokédex simples usando Golang e a Poke API. Você pode expandir este projeto adicionando mais recursos, como a capacidade de listar todos os Pokémon, salvar Pokémon favoritos ou até mesmo estilizar a interface para torná-la ainda mais parecida com a Pokédex original. Divirta-se explorando o mundo dos Pokémon!

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs