github.com/gramework/gramework@v1.8.1-0.20231027140105-82555c9057f5/sendfile.go (about) 1 // Copyright 2017-present Kirill Danshin and Gramework contributors 2 // Copyright 2019-present Highload LTD (UK CN: 11893420) 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 11 package gramework 12 13 // // Sendfile sends count bytes from f to remote a TCP connection. 14 // // f offset is always relative to the current offset. 15 // func Sendfile(conn *net.TCPConn, f *os.File, count int64) (n int64, err error) { 16 // lr := &io.LimitedReader{N: count, R: f} 17 // n, err = conn.ReadFrom(lr) 18 // return 19 // } 20 21 // // Sendfile tries to serve a file with sendfile() 22 // // otherwise fallbacks to slower copyZeroAlloc 23 // func (ctx *Context) Sendfile(filepath string) { 24 // ctx.Hijack(sendFileFunc(filepath)) 25 // } 26 27 // var ( 28 // internalServerErrorBytes = []byte("HTTP/1.1 500 Internal Server error\r\nConnection: close\r\n\r\nInternal Server Error") 29 // ) 30 31 // func sendFileFunc(filepath string) func(conn net.Conn) { 32 // return func(conn net.Conn) { 33 // f, err := os.Open(filepath) 34 // if err != nil { 35 // conn.Write(internalServerErrorBytes) 36 // } 37 // fi, err := f.Stat() 38 // if err != nil || fi.IsDir() { 39 // conn.Write(internalServerErrorBytes) 40 // } 41 // if tcpConn, ok := conn.(*net.TCPConn); ok { 42 // Sendfile(tcpConn, f, fi.Size()) 43 // log.Printf("Wow! So sendfile, much fast!") 44 // return 45 // } 46 47 // copyZeroAlloc(conn, f) 48 // } 49 // } 50 51 // func copyZeroAlloc(w io.Writer, r io.Reader) (int64, error) { 52 // vbuf := copyBufPool.Get() 53 // buf := vbuf.([]byte) 54 // n, err := io.CopyBuffer(w, r, buf) 55 // copyBufPool.Put(vbuf) 56 // return n, err 57 // } 58 59 // var copyBufPool = sync.Pool{ 60 // New: func() interface{} { 61 // return make([]byte, 4096) 62 // }, 63 // }