Go Web Examples
Basic
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc(
"/",
func(w http.ResponseWriter, r *http.Request) { // 1. A request handler
fmt.Fprintf(w, "Hello, you've requested: %s\n", r.URL.Path)
}
) // 2. Registering a handler to the default HTTP Server
http.ListenAndServe(":80", nil) // 3. start a HTTP server and listen for connections on port 80.
}
HTTP server
A basic HTTP server:
process dynamic requests.
serve static assets.
listen on a specific port to be able to accept connections from the internet.
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc(
"/",
func (w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to my website!")
}
)
// serve static assets
fs := http.FileServer(http.Dir("static/")) // define file server
http.Handle("/static/", http.StripPrefix("/static/", fs)) // 1. assign URL; 2. to serve files correctly, we need to strip away a part of the url path.
http.ListenAndServe(":80", nil)
}
You can read GET parameters with r.URL.Query().Get("token")
or POST form parameters with r.FormValue("email")
.
Routing
need gorilla/mux
$ go get -u github.com/gorilla/mux
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter() // create a new request router
router.HandleFunc(
"/books/{title}/page/{page}",
func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r) // get the data from these segments
title := vars["title"]
page := vars["page"]
fmt.Fprintf(w, "You've requested the book: %s on page %s\n", title, page)
}
)
http.ListenAndServe(":80", router) // nil = use the default router; here, we use 'router'
}
Templates
automatic escaping = no need to worry about about XSS attacks.
{{.}}
The dot is called the pipeline and the root element of the data.
package main
import (
"html/template"
"net/http"
)
type Todo struct {
Title string
Done bool
}
type TodoPageData struct {
PageTitle string
Todos []Todo
}
func main() {
tmpl := template.Must(template.ParseFiles("layout.html"))
// or: tmpl, err := template.ParseFiles("layout.html")
data := TodoPageData{
PageTitle: "My TODO list",
Todos: []Todo{
{Title: "Task 1", Done: false},
{Title: "Task 2", Done: true},
{Title: "Task 3", Done: true},
},
}
http.HandleFunc(
"/",
func(w http.ResponseWriter, r *http.Request) {
tmpl.Execute(w, data) // header: Content-Type: text/html; charset=utf-8
}
)
http.ListenAndServe(":80", nil)
}
<h1>{{.PageTitle}}<h1>
<ul>
{{range .Todos}}
{{if .Done}}
<li class="done">{{.Title}}</li>
{{else}}
<li>{{.Title}}</li>
{{end}}
{{end}}
</ul>
Assets and Files
Last updated
Was this helpful?