Go API Data Fetcher
This Go program demonstrates fetching data from an external API endpoint and displaying the response. It uses the net/http
package for making HTTP requests and the encoding/json
package for handling JSON data.
Fetching Data
The getDataFromExternalEndpoint
function retrieves data from the Chuck Norris API. Error handling is included to manage potential issues during the request and JSON parsing.
Handling the Response
The handler
function processes incoming requests, calls getDataFromExternalEndpoint
, and sends the JSON response back to the client. Error handling ensures that any errors are reported appropriately.
Main Function
The main
function sets up the HTTP server and listens for incoming requests on port 8080.
Example Usage
To run this program, save it as main.go
and execute it using go run main.go
. You can then access the fetched data by visiting http://localhost:8080
in your web browser.
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
type Response struct {
Data string `json:"value"`
}
func getDataFromExternalEndpoint() (*Response, error) {
url := "https://api.chucknorris.io/jokes/random"
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var response Response
err = json.Unmarshal(body, &response)
if err != nil {
return nil, err
}
return &response, nil
}
func handler(w http.ResponseWriter, r *http.Request) {
response, err := getDataFromExternalEndpoint()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(response)
}
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
Further Enhancements
This program can be extended to handle different API endpoints, data formats, and error conditions. Consider adding features like input validation, caching, and more sophisticated error handling for a production-ready application.
Consider adding more robust error handling and input validation for a production-ready application.
Explore other Go packages for enhanced functionality, such as improved logging and request timeout management.