Figuring out how to encode and send json data

This commit is contained in:
Curt Spark 2025-05-05 21:00:30 +01:00
parent c383e98bb8
commit f3ebd2a187
1 changed files with 18 additions and 7 deletions

25
main.go
View File

@ -1,8 +1,8 @@
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
@ -11,10 +11,26 @@ import (
"time"
)
type response struct {
Field1 string
Field2 string
}
func main() {
test_response := response{
Field1: "hi",
Field2: "there",
}
http.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Hi, ", r.Header)
w.Write([]byte("Hi there!"))
result, err := json.Marshal(test_response)
if err != nil {
log.Fatal(err)
}
w.Write(result)
})
http_server := &http.Server{
@ -28,11 +44,6 @@ func main() {
log.Fatal(http_server.ListenAndServe())
}()
fmt.Println("Server started! Listening in on ", http_server.Addr)
time.Sleep(1 * time.Second)
resp, _ := http.Get("http://127.0.0.1:8080/foo")
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)