ek-simple-api-example/go/api-example.go

47 lines
916 B
Go

package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
)
type HostnameResponse struct {
Hostname string `json:"hostname"`
}
func getHostnameHandler(w http.ResponseWriter, r *http.Request) {
hostname, err := os.Hostname()
if err != nil {
http.Error(w, "Error getting hostname", http.StatusInternalServerError)
return
}
response := HostnameResponse{
Hostname: hostname,
}
jsonData, err := json.Marshal(response)
if err != nil {
http.Error(w, "Error encoding response", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(jsonData)
}
func main() {
http.HandleFunc("/api/v1/getHostname", getHostnameHandler)
port := 8080
fmt.Printf("Server listening on port %d...\n", port)
err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
if err != nil {
fmt.Println("Error starting server:", err)
}
}