commit c89ee17329a2636e48b4ae39048e33f646abe691 Author: cdricms <36056008+cdricms@users.noreply.github.com> Date: Tue Jan 16 00:03:38 2024 +0100 Wow so easy diff --git a/api/api.go b/api/api.go new file mode 100644 index 0000000..9945258 --- /dev/null +++ b/api/api.go @@ -0,0 +1,27 @@ +package api + +import ( + "net/http" + "encoding/json" +) + +type User struct { + Username string `json:"username"` + Name string `json:"name"` + Age uint8 `json:"age"` +} + +func GetUserHandler(w http.ResponseWriter, r *http.Request) { + user := User{"johnnyBoy", "John Doe", 20} + jsonBytes, err := json.Marshal(user) + if err != nil { + http.Error(w, "Interal server error", http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "application/json") + _, _err := w.Write(jsonBytes) + if _err != nil { + http.Error(w, "Interal server error", http.StatusInternalServerError) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..8b39fe0 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.cems.dev/cdricms/go-api + +go 1.21.6 diff --git a/main.go b/main.go new file mode 100644 index 0000000..25a5f51 --- /dev/null +++ b/main.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" + "net/http" + + "git.cems.dev/cdricms/go-api/api" +) + +func main() { + http.HandleFunc("/user", api.GetUserHandler) + port := 8080 + fmt.Printf("Server running on : %d\n", port) + err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil) + if err != nil { + fmt.Println("Error: ", err) + } +}