用GO编译一个可以在openwrt上运行的http_server程序(在路由器上运行)

用GO编译一个可以在openwrt上运行的http_server程序

做个笔记,用GO编译一个路由器上可用的微型http_server程序:

GO语言比较新的版本都已经支持mipsle架构了,只需要在系统中定义两个系统变量就行编译


###具体步骤

各个系统的编译方法
1.Windows

set GOOS=linux
set GOARCH=mipsle
go build http_server.go

2.Linux/Uinx

env GOOS=linux GOARCH=mipsle go build http_server.go

代码:

网上找了找,再根据自己需要改的代码:

// http_server project main.go
package main

import (
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

var (
	port    = "66"  //默认端口
	wwwroot = "www" //网站根目录
)

func main() {
	startHTTP()
}

func startHTTP() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", IndexHandler)
	log.Println("HTTP Server Listening to 0.0.0.0: " + port)
	server := &http.Server{Addr: "0.0.0.0:" + port, Handler: mux}
	err := server.ListenAndServe()
	if err != nil {
		log.Fatal("ListenAndServe: ", err.Error())
	}
}

func IndexHandler(w http.ResponseWriter, r *http.Request) {
	if strings.HasPrefix(r.URL.String(), "/") {
		had := http.StripPrefix("/", http.FileServer(http.Dir(wwwroot)))
		had.ServeHTTP(w, r)
	} else {
		http.Error(w, "404 not found", 404)
	}

}

func getHtmlFile(path string) (fileHtml string) {
	dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	realPath := dir + "/" + wwwroot + "/" + path
	if PathExists(realPath) {
		file, err := os.Open(realPath)
		if err != nil {
			panic(err)
		}
		defer file.Close()
		fileContent, _ := ioutil.ReadAll(file)
		fileHtml = string(fileContent)

	} else {
		fileHtml = "404 page not found"
	}

	return fileHtml
}

func PathExists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}



GO就是这么干净利落,主要声明两个系统变量就行了,GO支持一下的系统架构搭配

	$GOOS       $GOARCH
    android     arm
    darwin      386
    darwin      amd64
    darwin      arm
    darwin      arm64
    dragonfly   amd64
    freebsd     386
    freebsd     amd64
    freebsd     arm
    linux       386
    linux       amd64
    linux       arm
    linux       arm64
    linux       ppc64
    linux       ppc64le
    linux       mips
    linux       mipsle
    linux       mips64
    linux       mips64le
    netbsd      386
    netbsd      amd64
    netbsd      arm
    openbsd     386
    openbsd     amd64
    openbsd     arm
    plan9       386
    plan9       amd64
    solaris     amd64
    windows     386
    windows     amd64

以后就可以编写更多方便的小工具运行在路由器上面了…

  • 参考链接1: https://studygolang.com/articles/12109?fr=sidebar

  • 参考链接2: https://www.cnblogs.com/jiashengmei/p/6371096.html

你可能感兴趣的:(GO语言,路由器编程)