github.com/google/fleetspeak@v0.1.15-0.20240426164851-4f31f62c1aea/fleetspeak/src/server/https/file_server.go (about)

     1  // Copyright 2017 Google Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     https://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package https
    16  
    17  import (
    18  	"fmt"
    19  	"net/http"
    20  	"net/url"
    21  	"strings"
    22  )
    23  
    24  // fileServer wraps a Communicator in order to serve files.
    25  type fileServer struct {
    26  	*Communicator
    27  }
    28  
    29  // ServeHTTP implements http.Handler
    30  func (s fileServer) ServeHTTP(res http.ResponseWriter, req *http.Request) {
    31  	path := strings.Split(strings.TrimPrefix(req.URL.EscapedPath(), "/"), "/")
    32  	if len(path) != 3 || path[0] != "files" {
    33  		http.Error(res, fmt.Sprintf("unable to parse files uri: %v", req.URL.EscapedPath()), http.StatusBadRequest)
    34  		return
    35  	}
    36  	service, err := url.PathUnescape(path[1])
    37  	if err != nil {
    38  		http.Error(res, fmt.Sprintf("unable to parse path component [%v]: %v", path[1], err), http.StatusBadRequest)
    39  		return
    40  	}
    41  	name, err := url.PathUnescape(path[2])
    42  	if err != nil {
    43  		http.Error(res, fmt.Sprintf("unable to parse path component [%v]: %v", path[2], err), http.StatusBadRequest)
    44  		return
    45  	}
    46  
    47  	ctx := req.Context()
    48  	data, modtime, err := s.fs.ReadFile(ctx, service, name)
    49  	if err != nil {
    50  		if s.fs.IsNotFound(err) {
    51  			http.Error(res, "file not found", http.StatusNotFound)
    52  			return
    53  		}
    54  		http.Error(res, fmt.Sprintf("internal error: %v", err), http.StatusInternalServerError)
    55  		return
    56  	}
    57  	http.ServeContent(res, req, name, modtime, data)
    58  	data.Close()
    59  }