Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.5 kB
1
Indexable
Never
func main() {
	router := http.ServeMux{}

	router.HandleFunc("/", (func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html")
		html := `
			<!DOCTYPE html>
			<html>
			<head>
				<title>Golang Template</title>
			</head>
			<body>
				{{ with $name := "Testing" }}
					<h1>
						{{ if or (eq "Testing" $name) (ne "Testing" $name) }} {{ "Hello Wordl" }}
						{{ else }} {{ $name }}
						{{ end }}
					</h1>
				{{ end }}

				<ul>
					<h4> Style loop 1 </h4>
						{{ range .Data }}
							<li> {{	.name }} </li>
						{{ end }}
				</ul>

				<ul>
				<h4> Style loop 2 </h4>
					{{ range $index, $data:= .Data }}
						<li> {{ $index }} {{	$data.name }} </li>
					{{ end }}
			</ul>
			</body>
			</html>
		`

		// html2 = `
		// 	<ul>
		// 		<h4>Style Loop Call 1</h4>
		// 		{{ range .Data }}
		// 			<li> {{ . }} </li>
		// 		{{ end }}
		// 	</ul>
		// 	<ul>
		// 		<h4>Style Loop Call 2</h4>
		// 		{{ range $data := .Data }}
		// 			<li> {{ $data }} </li>
		// 		{{ end }}
		// 	</ul>
		// `

		// arrData := []string{"senin", "selasa", "rabu", "kamis", "jumat", "sabtu", "minggu"}
		arrObjectData := []map[string]string{
			map[string]string{"name": "john doe"},
			map[string]string{"name": "jane doe"},
		}

		data := &ApiResponse{Code: http.StatusOK, Message: "Looping Array", Data: arrObjectData}

		temp := template.Must(template.New("index").Parse(html))
		temp.ExecuteTemplate(w, "index", data)
	}))

	err := http.ListenAndServe(":3000", &router)
	if err != nil {
		log.Fatal(err)
	}
}