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

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))
}
主站蜘蛛池模板: 房山区| 竹山县| 东丰县| 重庆市| 崇信县| 定边县| 那曲县| 龙川县| 通河县| 庆城县| 达拉特旗| 额尔古纳市| 新竹县| 海丰县| 松阳县| 新河县| 金堂县| 南昌县| 中牟县| 临西县| 南安市| 洛隆县| 阿勒泰市| 肃宁县| 岱山县| 岳池县| 大理市| 平泉县| 昌邑市| 凤山县| 那曲县| 石棉县| 合江县| 瑞昌市| 周口市| 阳信县| 蓬莱市| 凌源市| 司法| 临西县| 太白县|