"Go Language Programming Examples: Code Examples in Web Development"
With the rapid development of the Internet, Web development has become an indispensable part of various industries. . As a programming language with powerful functions and superior performance, Go language is increasingly favored by developers in web development. This article will introduce how to use Go language for Web development through specific code examples, so that readers can better understand and use Go language to build their own Web applications.
1. Simple HTTP server
First, let us start with a simple HTTP server. The following is a simple Go program that can implement a simple HTTP server:
package main import ( "fmt" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
In this example, we create an HTTP server and return "Hello, World!" under the root path "/" . Use the http.HandleFunc
function to register the handler function handler
, and then call http.ListenAndServe
to start the server and listen to the 8080 port.
2. Use a template engine to render pages
In actual Web development, a template engine is usually used to render dynamic pages. Here is an example code that uses the html/template
package from the Go standard library to render a page:
package main import ( "html/template" "net/http" ) type PageData struct { Title string Message string } func handler(w http.ResponseWriter, r *http.Request) { data := PageData{Title: "Welcome", Message: "Hello, World!"} tmpl := template.Must(template.New("index").Parse("<h1>{{.Title}}</h1><p>{{.Message}}</p>")) tmpl.Execute(w, data) } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
In this example, we define a PageData
structure body to store page data, then use the html/template
package to create a template, and pass the data to the template for rendering.
3. Use third-party frameworks
In addition to the functions provided by the Go standard library, you can also use third-party frameworks to simplify web development. A popular framework is gin
, here is a sample code using gin
framework:
package main import ( "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "Hello, World!", }) }) r.Run(":8080") }
In this example, we use gin
The framework creates a GET request handler and returns a JSON-formatted response.
Through the above examples, readers can learn how to use Go language for web development and master some common code examples. I hope this article will be helpful to readers who are learning or using Go language for web development.
The above is the detailed content of Go language programming examples: code examples in web development. For more information, please follow other related articles on the PHP Chinese website!