Figuring out how to encode and send json data
This commit is contained in:
parent
c383e98bb8
commit
f3ebd2a187
25
main.go
25
main.go
|
|
@ -1,8 +1,8 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
|
@ -11,10 +11,26 @@ import (
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type response struct {
|
||||||
|
Field1 string
|
||||||
|
Field2 string
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
test_response := response{
|
||||||
|
Field1: "hi",
|
||||||
|
Field2: "there",
|
||||||
|
}
|
||||||
|
|
||||||
http.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
|
http.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
|
||||||
fmt.Println("Hi, ", r.Header)
|
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{
|
http_server := &http.Server{
|
||||||
|
|
@ -28,11 +44,6 @@ func main() {
|
||||||
log.Fatal(http_server.ListenAndServe())
|
log.Fatal(http_server.ListenAndServe())
|
||||||
}()
|
}()
|
||||||
fmt.Println("Server started! Listening in on ", http_server.Addr)
|
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)
|
sigs := make(chan os.Signal, 1)
|
||||||
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
|
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue