/Evmosd-Faucet-Backend

This project is for evmosd command execution using Go-Posgres project.

Primary LanguageGo

Evmosd-Go-Postgres

This project is for evmosd command execution using Go-Posgres project. You can find original project in HERE.

Go-Postgres

This project(original) is simple CRUD application built in golang and using PostgreSQL as DB. This project is explained in this tutorial.

Pre-requisite

  1. Install golang v1.11 or above.(I am using v1.21 now)
  2. Basic understanding of the golang syntax.
  3. Basic understanding of SQL query.
  4. Code Editor (I recommend to use VS Code with Go extension by Microsoft installed)
  5. Postman for calling APIs

PostgreSQL Table

CREATE TABLE users (
  userid SERIAL PRIMARY KEY,
  name TEXT,
  age INT,
  location TEXT
);

Command Execution

import "os/exec"
func execute(params []string) []uint8{
  if len(params) == 0 {
    fmt.Println("No command provided")  
    return []uint8{0}
  }

  cmd := params[0]
  args := params[1:]

  out, err := exec.Command(cmd, args...).Output()

  if err != nil {
    fmt.Printf("%s\n", err)
    return []uint8{0}
  }

  return out
}
execute([]string{"evmosd", "tx", "bank", "send", original, address, "2000000000000aevmos", "--fees", "1400000aevmos", "-y"})

IP tracking

import "net/http"
func GetIP(r *http.Request) (string, error) {
  ips := r.Header.Get("X-Forwarded-For")
  splitIps := strings.Split(ips, ",")

  if len(splitIps) > 0 {
    // get last IP in list since ELB prepends other user defined IPs, meaning the last one is the actual client IP.
    netIP := net.ParseIP(splitIps[len(splitIps)-1])
    if netIP != nil {
      return netIP.String(), nil
    }
  }

  ip, _, err := net.SplitHostPort(r.RemoteAddr)
  if err != nil {
    return "", err
  }

  netIP := net.ParseIP(ip)
  if netIP != nil {
    ip := netIP.String()
    if ip == "::1" {
      return "127.0.0.1", nil
    }
    return ip, nil
  }

  return "", errors.New("IP not found")
}

HTTP Message

import {
  "net/http"
  "encoding/json"
}
func Main(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Access-Control-Allow-Origin", "*")  
  w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")  
  w.Header().Set("Access-Control-Allow-Headers", "Content-Type")  
  w.Header().Set("Content-Type", "application/json")
  if r.Method == http.MethodOptions {
    w.WriteHeader(http.StatusOK)
    return
  }
  if r.Method != http.MethodPost {
    http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  }

  var user models.User
  if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
    log.Fatalf("Unable to decode the request body.  %v", err)
  }

  res := main(user)
  
  if err := json.NewEncoder(w).Encode(res); err != nil {
    log.Fatalf("Unable to encode the request. %v", err)
  }
}

Thank you for Shubham Chadokar and Miguel Mota.