官术网_书友最值得收藏!

Installation

To install httprouter, we just need to run the get command:

go get github.com/julienschmidt/httprouter

So, now we have httprouter. We can refer to the library in our source code as this:

import "github.com/julienschmidt/httprouter"

The basic usage of httprouter can be understood through an example. In this example, let us create a small API to get information about files and programs installed from the server. Before jumping straight into the program, you should know how to execute system commands on Go. There is a package called os/exec. It allows us to execute system commands and get the output back to the program. 

import "os/exec"

Then it can be accessed in the code as this:

// arguments... means an array of strings unpacked as arguments in Go
cmd := exec.Command(command, arguments...)

exec.Command is the function that takes a command and an additional arguments array. Additional arguments are the options or input for the command. It can then be executed in two ways:

  • Run the command instantly
  • Start and wait for it to finish

We can collect the output of the command by attaching Stdout to a custom string. Get that string and send it back to the client. The code makes more sense here. Let us write a Go program to create a REST service that does two things:

  • Gets the Go version
  • Gets the file contents of a given file

This program uses Hhttprouter to create the service. Let us name it as execService.go:

package main
import (
"bytes"
"fmt"
"log"
"net/http"
"os/exec"
"github.com/julienschmidt/httprouter"
)
// This is a function to execute a system command and return output
func getCommandOutput(command string, arguments ...string) string {
// args... unpacks arguments array into elements
cmd := exec.Command(command, arguments...)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Start()
if err != nil {
log.Fatal(fmt.Sprint(err) + ": " + stderr.String())
}
err = cmd.Wait()
if err != nil {
log.Fatal(fmt.Sprint(err) + ": " + stderr.String())
}
return out.String()
}
func goVersion(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
fmt.Fprintf(w, getCommandOutput("/usr/local/bin/go", "version"))
}
func getFileContent(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
fmt.Fprintf(w, getCommandOutput("/bin/cat",
params.ByName("name")))
}
func main() {
router := httprouter.New()
// Mapping to methods is possible with HttpRouter
router.GET("/api/v1/go-version", goVersion)
// Path variable called name used here
router.GET("/api/v1/show-file/:name", getFileContent)
log.Fatal(http.ListenAndServe(":8000", router))
}
主站蜘蛛池模板: 冀州市| 武安市| 漠河县| 宿松县| 云和县| 巴东县| 城步| 雅安市| 宁城县| 化隆| 永顺县| 香河县| 观塘区| 建德市| 铅山县| 剑川县| 堆龙德庆县| 嘉荫县| 横山县| 兰州市| 手游| 章丘市| 平昌县| 福州市| 东丽区| 咸丰县| 六盘水市| 乃东县| 北票市| 西和县| 泰来县| 新田县| 宝鸡市| 剑阁县| 武邑县| 晋州市| 山东省| 翁牛特旗| 安泽县| 璧山县| 高雄县|