From f57813d16855173364a3669a2e98becd62471b6d Mon Sep 17 00:00:00 2001 From: FunctionsAPI Date: Mon, 27 Jan 2025 13:20:50 +0000 Subject: [PATCH] Automatic push from FunctionsAPI --- README.md | 3 +-- go.mod | 5 +++++ main.go | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 go.mod create mode 100644 main.go diff --git a/README.md b/README.md index a922e4b..4308772 100644 --- a/README.md +++ b/README.md @@ -1,2 +1 @@ -# cf31dcd24c2c41a4baf8651203c1aaa5 - +# go hello-world diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..9fe83cc --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module example.com/hello + +go 1.17 + +require github.com/OpenFunction/functions-framework-go v0.5.0 \ No newline at end of file diff --git a/main.go b/main.go new file mode 100644 index 0000000..26c2604 --- /dev/null +++ b/main.go @@ -0,0 +1,57 @@ +package hello + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "github.com/OpenFunction/functions-framework-go/functions" + +) + +// RequestData represents the JSON structure for incoming requests +type RequestData struct { + A int `json:"a"` + B int `json:"b"` +} + +// mainHandler handles HTTP requests and processes the data +func Main(w http.ResponseWriter, r *http.Request) { + log.Println("Function called with request") + + // Decode the JSON body into the RequestData struct + var data RequestData + err := json.NewDecoder(r.Body).Decode(&data) + if err != nil { + http.Error(w, "Invalid JSON payload", http.StatusBadRequest) + log.Println("Error decoding JSON:", err) + return + } + + log.Printf("Received data: %+v\n", data) + + // Compute the result + result := data.A + data.B + + // Prepare the response + response := map[string]int{"result": result} + + // Encode the response as JSON + w.Header().Set("Content-Type", "application/json") + err = json.NewEncoder(w).Encode(response) + if err != nil { + http.Error(w, "Error encoding response", http.StatusInternalServerError) + log.Println("Error encoding JSON:", err) + return + } + + log.Println("Response sent successfully") +} + +func init() { + // Set up the HTTP server + functions.HTTP("Main", Main, + functions.WithFunctionPath("/")) + + fmt.Println("Server is running on http://localhost:8080") +} \ No newline at end of file