Sunday, March 27, 2016

Convert struct to json. Then, output to the browser

Convert struct to json. Then, output to the browser

test.go:

package main

import (
  "fmt"
  "io"
  "net/http"
  "log"
  "encoding/json"
)

type Item struct {
  ItemName string
  ItemPrice int
}

type MyOrder struct {
  Status bool
  CustomerName string
  ItemArr []Item
}

func getOrder() (MyOrder) {
  item0 := Item {
    ItemName: "Computer",
    ItemPrice: 90,
  }

  order1 := MyOrder {
    Status: true,
    ItemArr: []Item{item0, Item {ItemName: "Pen", ItemPrice: 91}}, // initialize with two items.
  }

  return order1
}

func handler(w http.ResponseWriter, r *http.Request) {
  // we will demonstrate the different ways of outputing string to the browser in the code below.
  // So, we set the content type to text/plan.
  //w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  w.Header().Set("Content-Type", "text/plain; charset=UTF-8")

  // I am not sure what this line does. Leave it here for now.
  //w.WriteHeader(http.StatusOK)

  myorder := getOrder()
  //json.NewEncoder(w).Encode(myorder) // this line will actually output the json string to the browser. However, we wrap it in if for checking error.

  if err := json.NewEncoder(w).Encode(myorder); err == nil {
    // demonstrate the different ways of outputing string to the browser.
    str := "test"

    fmt.Fprintf(w, "This is the first method %v\n", str)

    io.WriteString(w, "This is the second method\n")

    w.Write([]byte("This is the third method\n"))
  } else {
    fmt.Printf("Here: %v\n", err) // this line will output the string to the console screen instead of the browser.
  }
}

func main() {
  http.HandleFunc("/", handler)

  err := http.ListenAndServe(":80", nil)

  if err != nil {
    fmt.Printf("main(): %s\n", err)
    log.Fatal("ListenAndServe: ", err)
  }
}

The output in Browser:

{"Status":true,"CustomerName":"","ItemArr":[{"ItemName":"Computer","ItemPrice":90},{"ItemName":"Pen","ItemPrice":91}]}

This is the first method test
This is the second method
This is the third method

Reference:

http://blog.ijun.org/2016/03/initialize-data-structure-and-convert.html

No comments: