package main
import (
“encoding/json”
“fmt”
“io”
“log”
“strings”
“net/http”
)
func Handle(w http.ResponseWriter,r *http.Request) {
const jsonStream= {"id": 1, "Name": "John", "Salary": 6000} {"id": 2, "Name": "Mark", "Salary": 7000} {"id": 3, "Name": "Sandy", "Salary": 8000} {"id": 4, "Name": "Holard","Salary": 2000}
type Employee struct {
id int json:"id"
Name string json:"name"
Salary int json:"salary"
}
dec := json.NewDecoder(strings.NewReader(jsonStream))
for {
var emp Employee
if err := dec.Decode(&emp); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
if emp.Salary>5000{
fmt.Fprintf(w," %d %s %d ",emp.id,emp.Name,emp.Salary)
}
}
}
func main(){
http.HandleFunc("/",Handle)
http.ListenAndServe(":8081",nil)
}
NobbZ
(Norbert Melzer)
May 31, 2018, 9:34am
2
A readable version of the code can be found at: https://play.golang.org/p/QdV7OhQPLg2
To achive your goal, there are some options.
use html/template
Write your table headers on the stream before you enter the loop, write columns to the stream in the loop, and write the tables footer after the loop.
edit
The first solution requires a little bit more of work, as it requires you to learn the template language as well, also you have to create a proper context to work with. But in the long term it will result in code that is easier to read, less cluttered and much easier to maintain.
1 Like
in the output Why I am Getting Zero inplace of id in the above program as specified %d ?
any suggestions
NobbZ
(Norbert Melzer)
June 1, 2018, 7:45am
4
id
is not an exposed field and therefore invisible to the reflection
package, which is used by the json
(un)marschaller to introspect the struct.
All fields that you want to use in JSON need to be exposed (begin with a capital letter).
2 Likes