Skip to content

Instantly share code, notes, and snippets.

@vyasriday
Forked from viveksyngh/server.go
Created December 24, 2020 07:24
Show Gist options
  • Select an option

  • Save vyasriday/ac8f4a8caa743ce6b06dd5725df755df to your computer and use it in GitHub Desktop.

Select an option

Save vyasriday/ac8f4a8caa743ce6b06dd5725df755df to your computer and use it in GitHub Desktop.
Http Response in go
package main
import (
"fmt"
"net/http"
"encoding/json"
"html/template"
)
type User struct {
Id int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Phone string `json:"phone"`
}
func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/json", jsonHandler)
http.HandleFunc("/template", templateHandler)
http.ListenAndServe(":8081", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World!")
}
//jsonHandler returns http respone in JSON format.
func jsonHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
user := User{Id: 1,
Name: "John Doe",
Email: "johndoe@gmail.com",
Phone: "000099999"}
json.NewEncoder(w).Encode(user)
}
//templateHandler renders a template and returns as http response.
func templateHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
t, err := template.ParseFiles("template.html")
if err != nil {
fmt.Fprintf(w, "Unable to load template")
}
user := User{Id: 1,
Name: "John Doe",
Email: "johndoe@gmail.com",
Phone: "000099999"}
t.Execute(w, user)
}
<html>
<head>
</head>
<body>
<h3>Name : {{.Name}}</h3>
<h3>Email : {{.Email}}</h3>
<h3>Phone : {{.Phone}}</h3>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment