-
-
Save vyasriday/ac8f4a8caa743ce6b06dd5725df755df to your computer and use it in GitHub Desktop.
Http Response in go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <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