Home  >  Article  >  Backend Development  >  Golang function library installation and usage guide

Golang function library installation and usage guide

PHPz
PHPzOriginal
2024-04-18 17:54:01918browse

Golang Function Library Installation and Usage Guide Install the function library: Download and install the function library through the go get command. Import function library: Use the import statement to import the function library so that it can be used by the program. Practical case: Use the gorilla/mux function library to create a REST API, including defining routes, processing functions and starting the server.

Golang function library installation and usage guide

Golang function library installation and usage guide

Installing function library

The installation of function libraries in Golang is very simple and can be completed through the go get command. This command will download and install the library in your GOPATH (Go working directory).

// 安装 github.com/gorilla/mux 路由函数库
go get github.com/gorilla/mux

Using the function library

After installing the function library, you can import the function library through the import statement. The import statement is placed at the beginning of the program file, for example:

import "github.com/gorilla/mux"

Then you can use the functions and types in the function library. For example, use mux.NewRouter() to create a new router:

func main() {
    router := mux.NewRouter()
}

Practical case: Use gorilla/mux to create a REST API

The following is A practical case of using the gorilla/mux function library to create a simple REST API.

main.go

package main

import (
    "fmt"
    "log"
    "net/http"
    "github.com/gorilla/mux"
)

func main() {
    // 创建路由器
    router := mux.NewRouter()
    router.HandleFunc("/users", getUsers).Methods(http.MethodGet)
    router.HandleFunc("/users/{id}", getSingleUser).Methods(http.MethodGet)

    // 启动 HTTP 服务器
    http.Handle("/", router)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func getUsers(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Get all users")
}

func getSingleUser(w http.ResponseWriter, r *http.Request) {
    id := mux.Vars(r)["id"]
    fmt.Fprintf(w, "Get user with ID: %s", id)
}

Run this program and browse to http://localhost:8080/users and http:/ /localhost:8080/users/1 to test the REST API.

The above is the detailed content of Golang function library installation and usage guide. 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