源码:
package main
import "net/http"
import (
"encoding/base64"
"fmt"
"io/ioutil"
)
func main() {
http.HandleFunc("/runcmd", handleRunCommand)
http.ListenAndServe("0.0.0.0:13388", nil)
}
func handleRunCommand(w http.ResponseWriter, r *http.Request){
if r.Method != http.MethodGet {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
}
imagePath := r.URL.Query().Get("imagePath")
if imagePath == "" {
http.Error(w, "Missing 'imagePath' parameter", http.StatusBadRequest)
}
base64 := runShellCommand(imagePath)
fmt.Println("base64测试handleRunCommand:"+base64)
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(base64))
}
func runShellCommand(imagePath string) (string) {
// 读取图片文件
imgData, err := ioutil.ReadFile(imagePath)
if err != nil {
fmt.Println("Read image file error:", err)
}
// 将图片二进制数据转换为 Base64 编码
imgBase64 := base64.StdEncoding.EncodeToString(imgData)
fmt.Println("imgBase64测试输出runShellCommand:"+imgBase64) // 输出 Base64 编码
return imgBase64
}
源码介绍:
首先我们是想通过go语言的main方法对外提供服务,前面代码是引入需要的包,然后写监听的方法名对外暴露的端口号,然后就是通过传入的imagePath图片路径获取对应的图片base64并返回,逻辑其实很简单,也是刚刚接触go语言。
部署运行:
其实想着用go语言是因为这个源码比如我们写在名为base64.go的记事本文件中,这个文件可以在linux服务器上编译成二进制程序并直接运行,比java要封装成服务运行起来要简单的多,毕竟我只需要一个简单的获取base64的功能,没有必要封装成一个项目打包运行,这也是用go的初衷,当然go语言还有很多其他的优点,等后面慢慢发现。
1.把base64.go源码文件放到/root路径下。
2.通过go build base64.go就可以把源码文件编译成名为base64的二进制文件,这里需要服务器有go指令才可以,具体请百度安装。
3.chmod 777 base64把这个二进制文件变成可执行的文件。
4. ./base64 &启动这个二进制程序。
5.启动成功后的访问路径http://服务器IP:暴露的端口号/runcmd?imagePath=服务器图片路径
这里用的是get请求封装的服务。