Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

求一个Scf Client #1

Open
wowulaile opened this issue Apr 12, 2021 · 2 comments
Open

求一个Scf Client #1

wowulaile opened this issue Apr 12, 2021 · 2 comments

Comments

@wowulaile
Copy link

大佬,能否提供个现成的client,编程苦手,调试了半天也没搞出来,跪求单播

@Sakurasan
Copy link
Owner

package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httputil"

	log "github.com/sirupsen/logrus"
)

var scfproxyUrl = "https://service.hk.apigw.tencentcs.com/release/scf-proxy"

func main() {
	fmt.Println("scf-proxy-client")
	m := http.NewServeMux()
	m.HandleFunc("/", scfproxy)
	http.ListenAndServe(":9000", m)
}

// DefineEvent 请求结构
type DefineEvent struct {
	URL     string `json:"url"`     // 目标的 URL, eg: http://cip.cc/
	Content string `json:"content"` // 最原始的 HTTP 报文, base64
}

// RespEvent 响应结构
type RespEvent struct {
	Status bool   `json:"status"` // 请求是否正常
	Error  string `json:"error"`  // 错误信息
	// Hander map[string]string `json:"Hander"`
	Data string `json:"data"` // HTTP 响应原始报文, base64
}

func scfproxy(w http.ResponseWriter, r *http.Request) {
	dumpReq, err := httputil.DumpRequest(r, true)
	if err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusServiceUnavailable)
		return
	}
	event := &DefineEvent{
		URL:     r.URL.String(),
		Content: base64.StdEncoding.EncodeToString(dumpReq),
	}
	bytejson, err := json.Marshal(event)
	if err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusServiceUnavailable)
		return
	}

	req, err := http.NewRequest("POST", scfproxyUrl, bytes.NewReader(bytejson))
	if err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusServiceUnavailable)
		return
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Println("client.Do()", err)
		w.WriteHeader(http.StatusServiceUnavailable)
		return
	}
	bytersp, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(bytersp))
	var respevent RespEvent
	if err := json.Unmarshal(bytersp, &respevent); err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusServiceUnavailable)
		return
	}
	if resp.StatusCode > 0 && resp.StatusCode != 200 {
		log.Println(err)
		w.WriteHeader(http.StatusServiceUnavailable)
		return
	}
	retByte, err := base64.StdEncoding.DecodeString(respevent.Data)
	if err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusServiceUnavailable)
		return
	}
	resp.Body.Close()

	w.Write(retByte)
	return
}

效果不太理想,你可以参考下,不支持https

@wowulaile
Copy link
Author

wowulaile commented Apr 15, 2021 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants