github.com/cloudwego/hertz@v0.9.3/pkg/common/adaptor/request.go (about) 1 /* 2 * Copyright 2022 CloudWeGo Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package adaptor 18 19 import ( 20 "bytes" 21 "net/http" 22 23 "github.com/cloudwego/hertz/pkg/protocol" 24 ) 25 26 // GetCompatRequest only support basic function of Request, not for all. 27 func GetCompatRequest(req *protocol.Request) (*http.Request, error) { 28 r, err := http.NewRequest(string(req.Method()), req.URI().String(), bytes.NewReader(req.Body())) 29 if err != nil { 30 return r, err 31 } 32 33 h := make(map[string][]string) 34 req.Header.VisitAll(func(k, v []byte) { 35 h[string(k)] = append(h[string(k)], string(v)) 36 }) 37 38 r.Header = h 39 return r, nil 40 } 41 42 // CopyToHertzRequest copy uri, host, method, protocol, header, but share body reader from http.Request to protocol.Request. 43 func CopyToHertzRequest(req *http.Request, hreq *protocol.Request) error { 44 hreq.Header.SetRequestURI(req.RequestURI) 45 hreq.Header.SetHost(req.Host) 46 hreq.Header.SetMethod(req.Method) 47 hreq.Header.SetProtocol(req.Proto) 48 for k, v := range req.Header { 49 for _, vv := range v { 50 hreq.Header.Add(k, vv) 51 } 52 } 53 if req.Body != nil { 54 hreq.SetBodyStream(req.Body, hreq.Header.ContentLength()) 55 } 56 return nil 57 }