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

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))
}
主站蜘蛛池模板: 黄山市| 奈曼旗| 通辽市| 勃利县| 桐庐县| 邹城市| 阜宁县| 延川县| 潢川县| 吉水县| 梧州市| 杂多县| 梧州市| 建水县| 徐州市| 鄂伦春自治旗| 余干县| 临城县| 灵台县| 封丘县| 甘泉县| 大兴区| 合肥市| 垦利县| 孝昌县| 株洲市| 陆丰市| 武强县| 西城区| 富顺县| 抚顺县| 科技| 霍州市| 潮州市| 集贤县| 钦州市| 富民县| 剑川县| 固安县| 阿尔山市| 虞城县|