golang 来自HTTP API的Docker运行命令(gin-gonic)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang 来自HTTP API的Docker运行命令(gin-gonic)相关的知识,希望对你有一定的参考价值。
package api
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
)
func Sdocker(c *gin.Context, image string, cmd ...string) {
args := append([]string{"run", "--rm", image}, cmd...)
out, err := exec.Command("docker", args...).CombinedOutput()
if err != nil {
c.JSON(500, gin.H{"message": err.Error()})
return
}
c.String(200, string(out))
}
func JSONdocker(c *gin.Context, image string, cmd ...string) {
args := append([]string{"run", "--rm", image}, cmd...)
out, err := exec.Command("docker", args...).CombinedOutput()
if err != nil {
c.JSON(500, gin.H{"message": fmt.Sprintf("%s (%s)", err.Error(), string(out))})
return
}
resp := make([]map[string]interface{}, 0)
err = json.Unmarshal(out, &resp)
if err != nil {
c.JSON(500, gin.H{"message": err.Error()})
return
}
c.JSON(200, resp)
}
golang Golang中的简单HTTP API
package main
import (
"fmt"
"log"
"net/http"
"os"
)
// main starts an HTTP server listening on $PORT which dispatches to request handlers.
func main() {
http.Handle("/healthz", http.HandlerFunc(healthcheckHandler))
// wrap the poweredByHandler with logging middleware
http.Handle("/", logRequestMiddleware(http.HandlerFunc(poweredByHandler)))
port := "8000"
log.Printf("listening on %v...\n", port)
err := http.ListenAndServe(":"+port, nil)
if err != nil {
panic(err)
}
}
// poweredByHandler writes "Powered by $POWERED_BY" to the response.
func poweredByHandler(w http.ResponseWriter, r *http.Request) {
hostname, _ := os.Hostname()
fmt.Fprintf(w, "Hello World! Container: %v", hostname)
}
// healthcheckHandler returns 200 for kubernetes healthchecks.
func healthcheckHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
// logRequestMiddleware writes out HTTP request information before passing to the next handler.
func logRequestMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
remote := r.RemoteAddr
if forwardedFor := r.Header.Get("X-Forwarded-For"); forwardedFor != "" {
remote = forwardedFor
}
log.Printf("%s %s %s", remote, r.Method, r.URL)
// pass the request to the next handler
next.ServeHTTP(w, r)
})
}
以上是关于golang 来自HTTP API的Docker运行命令(gin-gonic)的主要内容,如果未能解决你的问题,请参考以下文章
10分钟了解Docker,运维和开发视角有什么不同?
我如何编写处理来自 API 的响应/错误的 golang 中间件?
来自共享 Gitlab 运行器的 SSH 停止工作
golang Golang中的简单HTTP API
容器技术部署运维更快高效的发展就来自睿云智合(Wise2C)
golang web 方案