从文件读取HTTP标头的最有效方法?

时间:2019-01-02 10:46:30

标签: go

我正在寻找一种有效的方法来从文本文件中读取HTTP标头,然后再与HTTP请求一起发送。考虑以下代码(当前包含基本的net / http请求功能):

%My COM4
s = serial('COM4');
s.BaudRate = 9600;
s.DataBits = 8;
s.Parity ='none'; 
s.StopBits = 1;
s.FlowControl='none';
s.Terminator = ';';
s.ByteOrder = 'LittleEndian';
s.ReadAsyncMode = 'manual';

% Building write message.
devID = '02'; % device ID
cmd = 'S'; % command read or write; S for write
readM = cell(961,3);% Read at most 961-by-3 values filling a 961–by–3 matrix in column order

strF = num2str(i); 
strF = '11'; %pH parameter
strP = '15'; %pH set point
val = '006.8'; %pH set value 
msg_  = strcat('!', devID, cmd, strF, strP, val);%output the string
chksum = dec2hex(mod(sum(msg_),256)); %conversion to hexdec
msg = strcat(msg_,':', char(chksum), ';');

fopen(s); %connects s to the device using fopen , writes and reads text data
fwrite(s, uint8(msg)); %writes the binary data/ Convert to 8-bit unsigned integer (unit8) to the instrument connected to s.
reply=fscanf(s); %reads ASCII data from the device connected to the serial port object and returns it to reply, for binary data use fread
fclose(s); %Disconnect s from the scope, and remove s from memory and the workspace.

我是这样使用ioutil.ReadFile开始的:

func MakeRequest(target string, method string) {
client := &http.Client{}
req, _ := http.NewRequest(method, target, nil)

//Headers manually..
req.Header.Add("If-None-Match", `some value`)

response, _ := client.Do(req)
body, _ := ioutil.ReadAll(response.Body)
fmt.Println(string(body))
}

但是,采用此文本,将其拆分为一些指示符(让我们说“:”),然后将信息放入每个标头的req.Header.Add(“ var1”,“ var2”)似乎是一个过大的杀伤力。

问题:还有什么更好的方法来发送带有文本文件中标头的HTTP请求?

2 个答案:

答案 0 :(得分:3)

net/http具有方法ReadRequest,该方法可以从Request创建新的bufio.Reader对象。假设您的文件包含一个真实的HTTP请求(而不是仅包含key: value行的请求部分),您需要做的就是从文件中创建一个新的bufio.Reader,即这样(省略错误处理):

rdr,_ := os.Open("req.txt")
req,_ := http.ReadRequest(bufio.NewReader(rdr))
fmt.Printf("%+v\n", req)

答案 1 :(得分:1)

如果只想定义一些标头,则另一个选择是在Json文件中定义标头并应用以下代码(不包括文件读取):

var jsonMap map[string]string
err = json.Unmarshal(jsonBytesFromFile, &jsonMap)
if err != nil {
    log.Fatal("unable to parse json: ", err)
}

for k, v := range jsonMap {
    log.Printf("setting Header : %s : %s", k, v)
    responseWriter.Header().Add(k, v) // you may prefer Set()
}

json看起来像这样:

{ 
    "Content-type": "text/plain",
    "Cache-Control": "only-if-cached"
}