github.com/alexdevranger/node-1.8.27@v0.0.0-20221128213301-aa5841e41d2d/swarm/api/http/response.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of the go-dubxcoin library.
     3  //
     4  // The go-dubxcoin library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-dubxcoin library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-dubxcoin library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package http
    18  
    19  import (
    20  	"encoding/json"
    21  	"fmt"
    22  	"html/template"
    23  	"net/http"
    24  	"strings"
    25  	"time"
    26  
    27  	"github.com/alexdevranger/node-1.8.27/log"
    28  	"github.com/alexdevranger/node-1.8.27/metrics"
    29  	"github.com/alexdevranger/node-1.8.27/swarm/api"
    30  )
    31  
    32  var (
    33  	htmlCounter      = metrics.NewRegisteredCounter("api.http.errorpage.html.count", nil)
    34  	jsonCounter      = metrics.NewRegisteredCounter("api.http.errorpage.json.count", nil)
    35  	plaintextCounter = metrics.NewRegisteredCounter("api.http.errorpage.plaintext.count", nil)
    36  )
    37  
    38  type ResponseParams struct {
    39  	Msg       template.HTML
    40  	Code      int
    41  	Timestamp string
    42  	template  *template.Template
    43  	Details   template.HTML
    44  }
    45  
    46  // ShowMultipleChoices is used when a user requests a resource in a manifest which results
    47  // in ambiguous results. It returns a HTML page with clickable links of each of the entry
    48  // in the manifest which fits the request URI ambiguity.
    49  // For example, if the user requests bzz:/<hash>/read and that manifest contains entries
    50  // "readme.md" and "readinglist.txt", a HTML page is returned with this two links.
    51  // This only applies if the manifest has no default entry
    52  func ShowMultipleChoices(w http.ResponseWriter, r *http.Request, list api.ManifestList) {
    53  	log.Debug("ShowMultipleChoices", "ruid", GetRUID(r.Context()), "uri", GetURI(r.Context()))
    54  	msg := ""
    55  	if list.Entries == nil {
    56  		respondError(w, r, "Could not resolve", http.StatusInternalServerError)
    57  		return
    58  	}
    59  	requestUri := strings.TrimPrefix(r.RequestURI, "/")
    60  
    61  	uri, err := api.Parse(requestUri)
    62  	if err != nil {
    63  		respondError(w, r, "Bad Request", http.StatusBadRequest)
    64  	}
    65  
    66  	uri.Scheme = "bzz-list"
    67  	msg += fmt.Sprintf("Disambiguation:<br/>Your request may refer to multiple choices.<br/>Click <a class=\"orange\" href='"+"/"+uri.String()+"'>here</a> if your browser does not redirect you within 5 seconds.<script>setTimeout(\"location.href='%s';\",5000);</script><br/>", "/"+uri.String())
    68  	respondTemplate(w, r, "error", msg, http.StatusMultipleChoices)
    69  }
    70  
    71  func respondTemplate(w http.ResponseWriter, r *http.Request, templateName, msg string, code int) {
    72  	log.Debug("respondTemplate", "ruid", GetRUID(r.Context()), "uri", GetURI(r.Context()))
    73  	respond(w, r, &ResponseParams{
    74  		Code:      code,
    75  		Msg:       template.HTML(msg),
    76  		Timestamp: time.Now().Format(time.RFC1123),
    77  		template:  TemplatesMap[templateName],
    78  	})
    79  }
    80  
    81  func respondError(w http.ResponseWriter, r *http.Request, msg string, code int) {
    82  	log.Info("respondError", "ruid", GetRUID(r.Context()), "uri", GetURI(r.Context()), "code", code)
    83  	respondTemplate(w, r, "error", msg, code)
    84  }
    85  
    86  func respond(w http.ResponseWriter, r *http.Request, params *ResponseParams) {
    87  	w.WriteHeader(params.Code)
    88  
    89  	if params.Code >= 400 {
    90  		w.Header().Del("Cache-Control")
    91  		w.Header().Del("ETag")
    92  	}
    93  
    94  	acceptHeader := r.Header.Get("Accept")
    95  	// this cannot be in a switch since an Accept header can have multiple values: "Accept: */*, text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8"
    96  	if strings.Contains(acceptHeader, "application/json") {
    97  		if err := respondJSON(w, r, params); err != nil {
    98  			respondError(w, r, "Internal server error", http.StatusInternalServerError)
    99  		}
   100  	} else if strings.Contains(acceptHeader, "text/html") {
   101  		respondHTML(w, r, params)
   102  	} else {
   103  		respondPlaintext(w, r, params) //returns nice errors for curl
   104  	}
   105  }
   106  
   107  func respondHTML(w http.ResponseWriter, r *http.Request, params *ResponseParams) {
   108  	htmlCounter.Inc(1)
   109  	log.Info("respondHTML", "ruid", GetRUID(r.Context()), "code", params.Code)
   110  	err := params.template.Execute(w, params)
   111  	if err != nil {
   112  		log.Error(err.Error())
   113  	}
   114  }
   115  
   116  func respondJSON(w http.ResponseWriter, r *http.Request, params *ResponseParams) error {
   117  	jsonCounter.Inc(1)
   118  	log.Info("respondJSON", "ruid", GetRUID(r.Context()), "code", params.Code)
   119  	w.Header().Set("Content-Type", "application/json")
   120  	return json.NewEncoder(w).Encode(params)
   121  }
   122  
   123  func respondPlaintext(w http.ResponseWriter, r *http.Request, params *ResponseParams) error {
   124  	plaintextCounter.Inc(1)
   125  	log.Info("respondPlaintext", "ruid", GetRUID(r.Context()), "code", params.Code)
   126  	w.Header().Set("Content-Type", "text/plain")
   127  	strToWrite := "Code: " + fmt.Sprintf("%d", params.Code) + "\n"
   128  	strToWrite += "Message: " + string(params.Msg) + "\n"
   129  	strToWrite += "Timestamp: " + params.Timestamp + "\n"
   130  	_, err := w.Write([]byte(strToWrite))
   131  	return err
   132  }