Make Your First API in Golang

Install Go

cd /usr/local/src/
wget https://go.dev/dl/go1.21.5.linux-amd64.tar.gz
rm -rf /usr/local/go && tar -C /usr/local -xzf go1.21.5.linux-amd64.tar.gz
export PATH=$PATH:/usr/local/go/bin
cd 
go version

Start Writing API

mkdir /usr/local/hbapp/
cd /usr/local/hbapp/
vim main.go

copy the code

package main

import (
	"database/sql"
	"fmt"
	"log"
	"net/http"

	_ "github.com/go-sql-driver/mysql" // Import MySQL driver
	"github.com/gorilla/mux"
)

var db *sql.DB

func init() {
	var err error
	// Connect to your database
	db, err = sql.Open("mysql", "username:password@tcp(localhost:3306)/your_database")
	if err != nil {
		log.Fatal(err)
	}

	// Check if the connection is successful
	err = db.Ping()
	if err != nil {
		log.Fatal(err)
	}
}

func main() {
	r := mux.NewRouter()

	// Define your API endpoint
	r.HandleFunc("/check/{input}", CheckExistence).Methods("GET")

	// Start the HTTP server
	log.Fatal(http.ListenAndServe(":8080", r))
}

// CheckExistence is the handler for the API endpoint
func CheckExistence(w http.ResponseWriter, r *http.Request) {
	// Get the input parameter from the URL
	vars := mux.Vars(r)
	input := vars["input"]

	// Call a function to check if the input exists in the database
	exists, err := checkDatabase(input)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Return the result as JSON
	if exists {
		fmt.Fprint(w, `{"exists": true}`)
	} else {
		fmt.Fprint(w, `{"exists": false}`)
	}
}

// checkDatabase is a function to check if the input exists in the database
func checkDatabase(input string) (bool, error) {
	// Perform a query to check existence in your database
	// Replace "your_table" and "your_column" with your actual table and column names
	query := "SELECT COUNT(*) FROM your_table WHERE your_column = ?"
	var count int
	err := db.QueryRow(query, input).Scan(&count)
	if err != nil {
		return false, err
	}

	// If count is greater than 0, the input exists in the database
	return count > 0, nil
}

Install go modules

go install github.com/gorilla/mux@latest
go install github.com/go-sql-driver/mysql@latest

Compile your code

go mod init hbapp
go mod tidy
go build

Run the service with the following command

./hbapp

use the following command to test your API

curl http://your-ip:8080/check/{input}

Enjoy ;)

No comments:

Post a Comment

SIPp UAC Scenario to send RTP

Please install the latest sipp ( >=3.7.3 ) wget https://github.com/SIPp/sipp/releases/download/v3.7.3/sipp chmor +x sipp mv sipp /usr/bin...