Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· OpenAIAi2 WildChat-4.8M (AI2)

qt golang app to read arabic quran using api

  1. User

    qt golang app to read arabic quran using api

  2. Assistant

    Creating a simple Quran reading app in Golang using the Al-Quran Cloud API can be done by following these steps.

    1. Install the required packages:

    You will need the Gorilla Mux package for API handling and JSON parsing. To install Gorilla Mux, run the following command:

    go get -u github.com/gorilla/mux
    
    1. Prepare the code:

    Here is a complete code example for implementing the Quran reading app:

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"io/ioutil"
    	"net/http"
    	"strings"
    
    	"github.com/gorilla/mux"
    )
    
    type Ayah struct {
    	Text string `json:"text"`
    }
    
    type Data struct {
    	Ayahs []Ayah `json:"ayahs"`
    }
    
    type ApiResponse struct {
    	Data Data `json:"data"`
    }
    
    func FetchAyahs(surah int) (string, error) {
    	response, err := http.Get(fmt.Sprintf("https://api.alquran.cloud/v1/surah/%d", surah))
    	if err != nil {
    		return "", err
    	}
    	defer response.Body.Close()
    
    	body, err := ioutil.ReadAll(response.Body)
    	if err != nil {
    		return "", err
    	}
    
    	apiResponse := ApiResponse{}
    	err = json.Unmarshal(body, &apiResponse)
    	if err != nil {
    		return "", err
    	}
    
    	arabicText := []string{}
    	for _, ayah := range apiResponse.Data.Ayahs {
    		arabicText = append(arabicText, ayah.Text)
    	}
    
    	return strings.Join(arabicText, "\n"), nil
    }
    
    func main() {
    	r := mux.NewRouter()
    
    	r.HandleFunc("/surah/{id:[0-9]+}", func(w http.ResponseWriter, r *http.Request) {
    		vars := mux.Vars(r)
    		surahID := atoi(vars["id"])
    
    		ayahs, err := FetchAyahs(surahID)
    		if err != nil {
    			http.Error(w, "Failed to fetch Ayahs", http.StatusInternalServerError)
    			return
    		}
    
    		w.WriteHeader(http.StatusOK)
    		w.Write([]byte(ayahs))
    	})
    
    	http.ListenAndServe(":8000", r)
    }
    
    1. Build and run the application:

    To build the application, run the following commands:

    go build main.go
    

    To run the application, simply execute the binary that was created in the previous step:

    ./main
    
    1. Use the application:

    Start the application, and access it using a browser or any API client (like Postman). Make a GET request to the following endpoint to get the Arabic text for any Surah:

    http://localhost:8000/surah/{SURAH_NUMBER}
    

    Replace {SURAH_NUMBER} with the desired Surah number (1 to 114). It will return the Arabic text as a plain-text response.

    That's all! You now have a simple Golang app that can read the Arabic text of any Surah in the Quran using the Al-Quran Cloud API.