Skip to content

Instantly share code, notes, and snippets.

@imranismail
Last active June 10, 2018 12:27
Show Gist options
  • Save imranismail/247970db9549a06c8572766ff228ed71 to your computer and use it in GitHub Desktop.
Save imranismail/247970db9549a06c8572766ff228ed71 to your computer and use it in GitHub Desktop.
main.go
package main
import (
"flag"
"fmt"
"log"
"encoding/json"
"github.com/valyala/fasthttp"
)
var (
addr = flag.String("addr", ":4000", "TCP address to listen to")
)
type Image struct {
Url string `json:"url"`
Featured bool `json:"featured"`
Title string `json:"title"`
}
type Detail struct {
Title string `json:"title"`
Body string `json:"body"`
}
type Images []Image
type Details []Detail
type Product struct {
Title string `json:"name"`
Manufacturer string `json:"manufacturer"`
Images Images `json:"images"`
Details Details `json:"details"`
}
type Review struct {
Author string `json:"author"`
Comment string `json:"comment"`
Rating float64 `json:"rating"`
}
type Reviews []Review
type Merchant struct {
Name string `json:"name"`
CompanyRegNumber string `json:"company_reg_number"`
Rating float64 `json:"company_reg_number"`
Reviews Reviews
}
type Pricing struct {
Quantity int `json:"quantity"`
OriginalPrice string `json:"original_price"`
DiscountedPrice string `json:"discounted_price"`
}
type Response struct {
Product Product `json:"product"`
Merchant Merchant `json:"merchant"`
Pricing Pricing `json:"pricing"`
}
func main() {
flag.Parse()
h := requestHandler
if err := fasthttp.ListenAndServe(*addr, h); err != nil {
log.Fatalf("Error in ListenAndServe: %s", err)
}
}
func requestHandler(ctx *fasthttp.RequestCtx) {
resp := Response{
Product: Product{
Title: "Playstation 4 Pro",
Manufacturer: "Sony Entertainment",
Images: Images{
Image{Url: "https://unsplash.com/photos/uDXeC54RwV4", Featured: true, Title: "Playstation 4 Pro"},
},
Details: Details{
Detail{Title: "USB Ports", Body: "2"},
},
},
Merchant: Merchant{
Name: "Gamepit Sdn Bhd",
CompanyRegNumber: "1-337",
Rating: 4.9,
Reviews: Reviews{
Review{Author: "Imran I", Comment: "Product received in a very good condition", Rating: 5.0},
Review{Author: "Faiz M", Comment: "Subpar after sales service", Rating: 3.5},
Review{Author: "Gaddafi R", Comment: "Friendly staff, help me compare the drone specs", Rating: 5.0},
Review{Author: "Victor L", Comment: "Good product catalog", Rating: 5.0},
},
},
Pricing: Pricing{
Quantity: 1,
OriginalPrice: "RM 1200.99",
DiscountedPrice: "RM 1050.99",
},
}
b, err := json.Marshal(resp)
if err != nil {
panic(err)
}
fmt.Fprintf(ctx, string(b))
ctx.SetContentType("application/json; charset=utf-8")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment