Home  >  Article  >  Backend Development  >  golang does not require a framework

golang does not require a framework

王林
王林Original
2023-05-19 10:22:07486browse

golang is a statically typed programming language that supports concurrent programming. It performs extremely well when handling large numbers of concurrent web requests and can easily scale performance. Many people use some common web frameworks such as Beego, Gin, Martini, etc. when using golang, but we can write golang web programs without using these frameworks at all. The following will introduce how to implement web development in golang without using third-party frameworks.

  1. Use the native net/http package

golang’s standard library has encapsulated some http-related packages, such as net/http. This package can be used to implement http clients and servers. The following is a simple http server implementation:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintf(w, "Hello World")
    })

    http.ListenAndServe(":8080", nil)
}

Set the route through the http.HandleFunc method. The parameters include the access path and response processing function. Online applications that need to use TLS (Transport Layer Security) authentication mechanism can use the http.ListenAndServeTLS() method.

  1. Use the native template package

golang’s standard library also has a template engine template, which is a template rendering mechanism provided by golang. It supports parsing and execution The behavior is defined in the action instructions inside ”{{}}”. In this way, data can be easily filled into the specified template.

The following is an example of using template:

package main

import (
    "html/template"
    "net/http"
)

func main() {
      http.HandleFunc("/", viewHandler)
      http.ListenAndServe(":8080", nil)
}

func viewHandler(writer http.ResponseWriter, request *http.Request) {
      // 首先定义一个模板字符串
      const myTemplateString = `
              <!DOCTYPE html>
              <html lang="en">
              <head>
                  <meta charset="UTF-8">
                  <title>{{.Title}}</title>
              </head>
              <body>
              {{if .IsUser}}
                  <h1>Hello {{.UserName}}!</h1>
              {{else}}
                  <h1>Hello guest!</h1>
              {{end}}
              </body>
              </html>`
      // 定义一个结构体,用于填充模板
      type MyTemplateData struct {
              Title    string // 页面标题
              IsUser   bool   // 是否是已经登录的用户
              UserName string // 用户名
      }
      // 填充模板
      t, err := template.New("myTemplateString").Parse(myTemplateString)
      if err != nil {
              panic(err)
      }
      data := MyTemplateData{
              Title:    "My Awesome Page",
              IsUser:   true,
              UserName: "Gopher",
      }
      t.Execute(writer, data)
}

In this example, a template string is first defined, and then a structure is defined to represent the data to fill the template. Finally, the template is parsed through the template.New method, the data is filled in and the results are output to the browser.

  1. Use the native sql package

Golang can also use the native sql package to operate databases such as MySQL. Encapsulated sql.DB to support connection pooling and thread safety. The following is an example of using golang's native sql package:

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
      db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/database")
      if err != nil {
              fmt.Println(err)
      }
      defer db.Close()

      // 查询数据库
      rows, err := db.Query("SELECT * FROM users")
      if err != nil {
              fmt.Println(err)
      }
      defer rows.Close()

      for rows.Next() {
              var id int
              var name string
              err = rows.Scan(&id, &name)
              if err != nil {
                      fmt.Println(err)
              }
              fmt.Printf("id: %d, name: %s
", id, name)
      }
}

In this example, sql.Open() is used to open a MySQL link and then execute a query statement SELECT * FROM users, traverse multiple records returned by the query result set through rows.Next().

As can be seen from the above three examples, golang can also complete web development without using third-party frameworks. You can find the libraries you need to use for web development based on your needs. Of course, when writing web projects, it is recommended to use a third-party framework with good encapsulation and documentation support. After all, from a process and efficiency perspective, a third-party framework will be more convenient and efficient.

The above is the detailed content of golang does not require a framework. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:golang startup processNext article:golang startup process