Thursday, 29 October 2020

go web app 12 json response

 
get json response from go server
//main.go
package main

import (
"encoding/json"
"html/template"
"net/http"

"github.com/gorilla/mux"
)

type car struct {
Color   string
Mileage int
Model   string
}

var templates *template.Template

var truck = car{
Color:   "black",
Mileage: 12345,
Model:   "F-150",
}

var sedan = car{
Color:   "white",
Mileage: 321,
Model:   "Corolla",
}

func indexGetHandler(w http.ResponseWriter, r *http.Request) {
//templates.ExecuteTemplate(w, "index.html", []car{truck, sedan})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode([]car{truck, sedan})
}

func main() {
templates = template.Must(template.ParseGlob("templates/*.html"))
r := mux.NewRouter()
r.HandleFunc("/", indexGetHandler).Methods("GET")
//r.HandleFunc("/", indexPostHandler).Methods("POST")
http.Handle("/", r)
http.ListenAndServe(":8000", nil)
}

No comments:

Post a Comment